Navigation

Java Operators

Java Operators

1. Operators

Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result.

2. Operator Precedence

As we explore the operators of the Java programming language, it may be helpful for you to know ahead of time which operators have the highest precedence. The operators in the following table are listed according to precedence order.

Operators with higher precedence are evaluated before operators with relatively lower precedence.

When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.

Operator Precedence
Operators Precedence
postfix expr++ expr--
unary ++expr --expr +expr -expr ~ !
multiplicative * / %
additive + -
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ? :
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

3. The Assignment Operator

One of the most common operators that you'll encounter is the simple assignment operator "=".

                int speed = 0;
                int gear = 1;
            

This operator can also be used on objects to assign object references.

4. The Arithmetic Operator

The Java programming language provides operators that perform addition, subtraction, multiplication, and division. The only symbol that might look new to you is "%", which divides one operand by another and returns the remainder as its result.

Arithmetic Operator
Operator Description
+ Additive operator (also used for String concatenation)
- Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator

Example for Arithmetic Operator

                    /**
                     * A Class used to demonstrate Arithmetic Operators.
                     * 
                     * @author vasanth
                     *
                     */
                    public class ArithmeticOperatorDemo {

                        /**
                         * Main.
                         * 
                         * @param args
                         */
                        public static void main(String[] args) {

                            // Initialize Two numbers.
                            int num1 = 10;
                            int num2 = 3;

                            // Create variable to save result.
                            int result;

                            // 1. Addition '+'.
                            result = num1 + num2;
                            System.out.println(num1 + " + " + num2 + " = " + result);

                            // 2. Subtraction '-'.
                            result = num1 - num2;
                            System.out.println(num1 + " - " + num2 + " = " + result);

                            // 3. Multiplication '*'.
                            result = num1 * num2;
                            System.out.println(num1 + " * " + num2 + " = " + result);

                            // 4. Division '/'.
                            result = num1 / num2;
                            System.out.println(num1 + " / " + num2 + " = " + result);

                            // 1. modulus '%'.
                            result = num1 % num2;
                            System.out.println(num1 + " % " + num2 + " = " + result);

                        }
                    }
                

Output

    10 + 3 = 13
    10 - 3 = 7
    10 * 3 = 30
    10 / 3 = 3
    10 % 3 = 1

5. The Unary Operator

The unary operators require only one operand; they perform various operations such as incrementing/decrementing a value by one, negating an expression, or inverting the value of a boolean.

Unary Operator
Operator Description
+ Unary plus operator; indicates positive value (numbers are positive without this, however)
- Unary minus operator; negates an expression
++ Increment operator; increments a value by 1
-- Decrement operator; decrements a value by 1
! Logical complement operator; inverts the value of a boolean

Example for Unary Operator

                /**
                 * A Class used to demonstrate Unary Operator
                 * 
                 * @author vasanth
                 *
                 */
                public class UnaryOperatorDemo {

                    /**
                     * Main.
                     * 
                     * @param args
                     */
                    public static void main(String[] args) {

                        // Create variables.
                        int num1;
                        int result;

                        // 1. Unary plus operator '+'.
                        num1 = 1;
                        result = +(num1);
                        System.out.println("+ (" + num1 + ") = " + result);

                        // 2. Unary minus operator '-'.
                        num1 = 1;
                        result = -(num1);
                        System.out.println("- (" + num1 + ") = " + result);

                        // 3. Increment operator '++'.
                        num1 = 1;
                        result = ++num1;
                        System.out.println("++ 1 = " + result);

                        // 4. Decrement operator '--'.
                        num1 = 1;
                        result = --num1;
                        System.out.println("-- 1 = " + result);

                        // 5. Logical complement operators '!'.
                        boolean inputBoolean = true;
                        boolean resultBoolean = !(inputBoolean);
                        System.out.println("!(true) = " + resultBoolean);
                    }
                }
             

Output

    + (1) = 1
    - (1) = -1
    ++ 1 = 2
    -- 1 = 0
    !(true) = false

Post increment/decrement (n++ / n--) and Pre increment/decrement (++n/ n--)

The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value.

Post Increment (n++) : First execute the statement then increase the value by one.

Pre Increment (++n) : First increase the value by one then execute the statement.

Example for Post & Pre Increment

                /**
                 * A Class used to demonstrate difference between
                 * 
                 * @author vasanth
                 *
                 */
                public class PrePostDemo {

                    /**
                     * Main.
                     * 
                     * @param args
                     */
                    public static void main(String[] args) {
                        System.out.println("***Post increment test***");
                        int n = 10;
                        System.out.println(n); // output 10
                        System.out.println(n++); // output 10
                        System.out.println(n); // output 11

                        System.out.println("***Pre increment test***");
                        int m = 10;
                        System.out.println(m); // output 10
                        System.out.println(++m); // output 11
                        System.out.println(m); // output 11
                    }
                }
            

Output

    ***Post increment test***
    10
    10
    11
    ***Pre increment test***
    10
    11
    11

6. The Equality & Relational Operator

The equality and relational operators determine if one operand is greater than, less than, equal to, or not equal to another operand.

Keep in mind that you must use "==", not "=", when testing if two primitive values are equal.

    ==      equal to
    !=      not equal to
    >       greater than
    >=      greater than or equal to
    <       less than
    <=      less than or equal to

Example for Comparison Operator

                /**
                 * A Class used to demonstrate Comparison Operator.
                 * 
                 * @author vasanth
                 *
                 */
                public class ComparisonOperatorDemo {

                    /**
                     * Main.
                     * 
                     * @param args
                     */
                    public static void main(String[] args) {
                        int value1 = 1;
                        int value2 = 2;
                        if (value1 == value2)
                            System.out.println("value1 == value2");
                        if (value1 != value2)
                            System.out.println("value1 != value2");
                        if (value1>value2)
                            System.out.println("value1 > value2");
                        if (value1<value2)
                            System.out.println("value1 < value2");
                        if (value1<= value2)
                            System.out.println("value1 <= value2");
                    }
                }
            

Output

    value1 != value2
    value1 < value2
    value1 <= value2

7. The Conditional Operator

The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean expressions.

These operators exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed.

&& Conditional-AND

|| Conditional-OR

Conditional Operator
A B A && B A || B
False False False False
False True False True
True False False True
True True True True

Example for Conditional Operator

                /**
                 * A Class used to demonstrate Conditional Operator.
                 * 
                 * @author vasanth
                 *
                 */
                public class ConditionalOperatorDemo {

                    /**
                     * Main.
                     * 
                     * @param args
                     */
                    public static void main(String[] args) {
                        int value1 = 1;
                        int value2 = 2;
                        if ((value1 == 1) && (value2 == 2))
                            System.out.println("value1 is 1 AND value2 is 2");
                        if ((value1 == 1) || (value2 == 1))
                            System.out.println("value1 is 1 OR value2 is 1");
                    }
                }
            

Output

    value1 is 1 AND value2 is 2
    value1 is 1 OR value2 is 1

Ternary Operator

Another conditional operator is ?:, which can be thought of as shorthand for an if-then-else statement (discussed in later lesson). This operator is also known as the ternary operator because it uses three operands.

In the following example, this operator should be read as: "If someCondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result."

Example for Ternary Operator

            /**
             * A Class used to demonstrate Ternary Operator.
             * 
             * @author vasanth
             *
             */
            public class TernaryOperatorDemo {

                /**
                 * Main.
                 * 
                 * @param args
                 */
                public static void main(String[] args) {
                    int value1 = 1;
                    int value2 = 2;
                    int result;
                    boolean someCondition = true;
                    result = someCondition ? value1 : value2;

                    System.out.println(result);
                }
            }
            

Output

    1

Because someCondition is true, this program prints "1" to the screen. Use the ?: operator instead of an if-then-else statement if it makes your code more readable.

8. The Type Comparison Operator instanceof

The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

The following program, InstanceofDemo, defines a parent class (named Parent), a simple interface (named MyInterface), and a child class (named Child) that inherits from the parent and implements the interface.

Example for instanceof

                /**
                 * A Class used to demonstrate InstanceOf Operator.
                 * 
                 * @author vasanth
                 *
                 */
                public class InstanceOfOperatorDemo {

                    /**
                     * Main.
                     * 
                     * @param args
                     */
                    public static void main(String[] args) {
                        Parent obj1 = new Parent();
                        Parent obj2 = new Child();

                        System.out.println("obj1 instanceof Parent: "
                                + (obj1instanceof Parent));
                        System.out.println("obj1 instanceof Child: " + (obj1instanceof Child));
                        System.out.println("obj1 instanceof MyInterface: "
                                + (obj1instanceof MyInterface));
                        System.out.println("obj2 instanceof Parent: "
                                + (obj2instanceof Parent));
                        System.out.println("obj2 instanceof Child: " + (obj2instanceof Child));
                        System.out.println("obj2 instanceof MyInterface: "
                                + (obj2instanceof MyInterface));
                    }
                }
                class Parent {}
                class Child extends Parent implements MyInterface {}
                interface MyInterface {}
            

Output

    obj1 instanceof Parent: true
    obj1 instanceof Child: false
    obj1 instanceof MyInterface: false
    obj2 instanceof Parent: true
    obj2 instanceof Child: true
    obj2 instanceof MyInterface: true

When using the instanceof operator, keep in mind that null is not an instance of anything.

9. Bitwise and Bit Shift Operators

Bitwise and Bit Shift operators in Java are powerful set of operators which allows you to manipulate bits on integral types like int, long, short, bytes and boolean data types in Java.

Basics

Before exploring bitwise and bit shift operator in Java, its prerequisite that you must be familiar with binary format.

  1. Binary format has just two bit, 0 and 1 and that's why is called binary.

  2. In binary arithmetic :

    0 + 0 = 0

    0 + 1 = 1

    1 + 0 = 1

    1 + 1 = 10

  3. Integral types in Java (int, long, short and byte) are signed numbers in Java where most significant bit (MSB) represent sign of number. 1 will denote a negative number and 0 as MSB will denote a positive numbers.

  4. Negative numbers in Java are represented as 2's complement of number. 2's complement of a number is 1's complement + 1 and 1's complement means all zero will turn to 1 and all 1 turned to zero in a binary number e.g. 1's complement of 10 would be 01. and 2's complement of 10 would be 10+1 = 11 (all in binary).

Bitwise operators in Java

In this section we will see example of each of bitwise operator e.g. bitwise negation or complement operator (~), bitwise AND (&), bitwise OR(|) and bitwise XOR(^) operator in Java.

Bitwise unary complement operator (~)

The unary bitwise complement operator "~" inverts a bit pattern; it can be applied to any of the integral types, making every "0" a "1" and every "1" a "0".

Example

                int number = 2; // 0010
                System.out.println(" value of number before: " + number); //0010 
                System.out.println(" value of number after negation: " + ~number); //1101
            

Ouput

    value of number before: 2
    value of number after negation: -3

Bitwise AND operator (&)

The bitwise & operator performs a bitwise AND operation.

Bitwise AND operator
A B A & B
0 0 0
0 1 0
1 0 0
1 1 1

Example

                int a = 2; // 0010
                int b = 4; // 0100

                System.out.println("Result of a&b  is " + (a & b)); // 0000
            

Output

    Result of a&b  is 0

Bitwise OR operator (|)

The bitwise | operator performs a bitwise inclusive OR operation.

Bitwise OR operator
A B A | B
0 0 0
0 1 1
1 0 1
1 1 1

Example

                int a = 2; // 0010
                int b = 4; // 0100

                System.out.println(" value of A bitwise OR B in Java : " + (a | b)); // 0110

            

Output

    value of A bitwise OR B in Java : 6

Bitwise XOR operator (^)

The bitwise ^ operator performs a bitwise exclusive OR operation.

Bitwise XOR operators will return 1 if both bits are different and return 0 if both bits are same.

Bitwise XOR operator
A B A ^ B
0 0 0
0 1 1
1 0 1
1 1 0

Example

                int a = 2; // 0010
                int b = 4; // 0100

                System.out.println(" value of a XOR B in Java : " + (a ^ b)); // 0110
            

Output

    value of a XOR B in Java : 6

Bit Shift Operators

Bit shift operators, which can be used to shift bit from one position to another on both left and right side in a number.

An int in Java ranges from the pattern:

10000000000000000000000000000000 (in decimal it's the number -2147483648)

To the pattern:

01111111111111111111111111111111 (in decimal it's the number 2147483647)

We can see how the integer numbers has been expressed in binary format,

+8 : 1000

-8 : 1111 1111 1111 1111 1111 1111 1111 1000

You can see above that positive number is straightforward but negative number has been expressed in 2’s compliment.

Negative numbers in Java are represented as 2's complement of number. 2's complement of a number is 1's complement + 1 and 1's complement means all zero will turn to 1 and all 1 turned to zero in a binary number.

Example to find binary representation of -8:

  • Binary representation of 8 = 0000 0000 0000 0000 0000 0000 0000 1000

  • 1's complement of 8 = 1111 1111 1111 1111 1111 1111 1111 0111

  • 2's complement of 8 = -8 = (1's complement of 8) + 1 = 1111 1111 1111 1111 1111 1111 1111 1000

To represent a negative number in base 2, we have a control bit, that is the bit that stays most to the left, so if a binary number starts with 1, we’re talking about a negative number, if it starts with a 0, we’re talking about a positive one.

Java provides three bit shift operator,

  • Signed left shift operator " << "

  • Signed right shift operator ">>"

  • Unsigned right shift operator ">>>".

As per syntax of bitshift operator, left hand side of operand is the number whose bit needs to be shift and right hand side of operator is how many bits needs to shift.

Example : (n >> 1)

Left Shift Operator "<<"

Left shift operator with sign, shifts bit into left.

Left shift operator (<<) is used to shift a bit pattern to the left preserving the sign bit.

Left shift operator (<<) is used to shift a bit pattern to the left preserving the sign bit, which means that everything else gets shifted, but the control bit stays put. If it was a 0 it remains as 0, and if it was a 1 it remains as 1.

Example :

    +9 << 2
    +9  = 0 0000 1001
    +9 << 2 = 0 0010 0100 = 36

Example :

    -9 << 2
    -9 = 1 1111 0111 (Expressed in 2’s Complement)
    -9 << 2 = 1 1101 1100 = -36

Explanation :

-9 is expressed as :

1 1 1 1 1 0 1 1 1

Shift two bits left

1 1 1 0 1 1 1 0 0

Since MSB (Most Significant Bit) is 1, hence result is negative number so apply 2’s complement to get actual number.

2’s Complement of 1101 1100 = 0010 0100 = -36

Don’t take in account MSB.

Left Shift Operator
Number Number << 1
8 (0000 0000 0000 0000 0000 0000 0000 1000) 16 (0000 0000 0000 0000 0000 0000 0001 0000)
-8 (1111 1111 1111 1111 1111 1111 1111 1000) -16 (1111 1111 1111 1111 1111 1111 1111 0000)

Example

                    int number = 8; // 0000 1000
                    System.out.println("Original number : " + number);

                    // left shifting bytes with 1 position
                    number = number << 1; // should be 16 i.e. 0001 0000

                    // equivalent of multiplication of 2
                    System.out.println("value of number after left shift: " + number);
                

Output

    Original number : 8
    value of number after left shift: 16

Right Shift Operator ">>"

Right shift operator with sign, shifts the bit on right side.

Right shift operator (>>) is used to shift a bit pattern to the right preserving the sign bit.

Right shift operator (>>) is used to shift a bit pattern to the right preserving the sign bit, which means that everything else gets shifted, but the control bit stays put. If it was a 0 it remains as 0, and if it was a 1 it remains as 1.

Example :

    -9 >> 2
    -9 = 1 1111 0111 (Expressed in 2’s Complement)
    -9 >> 2 = 1 1101 1100 = -36

Example :

    -9  >> 2
    -9 = 1 1111 0111 (Expressed in 2’s Complement)
    -9 >> 2 = 1 1111 1101 = -3

Explanation :

-9 is expressed as :

1 1 1 1 1 0 1 1 1

Shift two bits right

1 1 1 1 1 1 1 0 1

Since MSB (Most Significant Bit) is 1, hence result is negative number so apply 2’s complement to get actual number.

2’s Complement of 1111 1101 = 0000 0011 = -3

Don’t take in account MSB.

Right Shift Operator
Number Number >> 1
8 (0000 0000 0000 0000 0000 0000 0000 1000) 4 (0000 0000 0000 0000 0000 0000 0000 0100)
-8 (11111111111111111111111111111000) -4 (11111111111111111111111111111100)

Example

                    int number = 8; // 0000 1000
                    System.out.println("Original number : " + number);

                    // right shifting bytes with sign 1 position
                    number = number >> 1; // should be 4 i.e. 0000 0100

                    // equivalent of division of 2
                    System.out.println("value of number after right shift with sign: " + number);
                

Output

    Original number : 8
    value of number after right shift with sign: 4

Unsigned Right Shift Operator ">>>"

Unsigned right shift operator ">>>" right shift without sign operator will only shift the bit towards right without preserving sign of number.

Unsigned right shift operator ">>>" does not preserve the sign bit, everything gets shifted, no matter where it is.

For positive number it is straightforward i.e. bits gets shifted to the right.

But for Negative number also bits get shifted to the right, hence sign of the number is not preserved.

Unsigned Right Shift Operator
Number Number >>> 1
8 (0000 0000 0000 0000 0000 0000 0000 1000) 4 (0000 0000 0000 0000 0000 0000 0000 0100)
-8 (1111 1111 1111 1111 1111 1111 1111 1000) 2147483644 (0111 1111 1111 1111 1111 1111 1111 1100)

Example

                    int number = -8; // 1111 1111 1111 1111 1111 1111 1111 1000
                    System.out.println("Original number : " + number);

                    // unsigned right shifting bytes with out sign 1 position
                    number = number >>> 1; // should be 2147483644 i.e. 0111 1111 1111 1111 1111 1111 1111 1100

                    System.out.println("value of number after unsigned right shift with out sign: " + number);
            

Output

    Original number : -8
    value of number after unsigned right shift with out sign: 2147483644

No comments:

Post a Comment