Easy Tutorial
❮ Java Abstraction Java Arraylist Retainall ❯

Java Operators

One of the most basic uses of a computer is to perform mathematical operations. As a computer language, Java provides a rich set of operators to manipulate variables. We can divide operators into the following groups:

Arithmetic Operators

Arithmetic operators are used in mathematical expressions and function similarly to how they do in mathematics. The following table lists all the arithmetic operators.

The examples in the table assume that the integer variable A has a value of 10 and variable B has a value of 20:

Operator Description Example
+ Addition - Adds values on either side of the operator A + B equals 30
- Subtraction - Subtracts the right operand from the left operand A – B equals -10
* Multiplication - Multiplies values on either side of the operator A * B equals 200
/ Division - Divides the left operand by the right operand B / A equals 2
% Modulus - Returns the remainder of the division of the left operand by the right operand B % A equals 0
++ Increment - Increases the value of the operand by 1 B++ or ++B equals 21 (see details below)
-- Decrement - Decreases the value of the operand by 1 B-- or --B equals 19 (see details below)

Example

The following simple example program demonstrates arithmetic operators. Copy and paste the following Java program into a file named Test.java, compile, and run this program:

public class Test {

  public static void main(String[] args) {
     int a = 10;
     int b = 20;
     int c = 25;
     int d = 25;
     System.out.println("a + b = " + (a + b) );
     System.out.println("a - b = " + (a - b) );
     System.out.println("a * b = " + (a * b) );
     System.out.println("b / a = " + (b / a) );
     System.out.println("b % a = " + (b % a) );
     System.out.println("c % a = " + (c % a) );
     System.out.println("a++   = " +  (a++) );
     System.out.println("a--   = " +  (a--) );
     // See the difference between d++ and ++d
     System.out.println("d++   = " +  (d++) );
     System.out.println("++d   = " +  (++d) );
  }
}

The compilation and execution of the above example result in the following output:

a + b = 30
a - b = -10
a * b = 200
b / a = 2
b % a = 0
c % a = 5
a++   = 10
a--   = 11
d++   = 25
++d   = 27

Increment and Decrement Operators

1. Increment (++) and Decrement (--) Operators are special arithmetic operators that require only one operand.

public class selfAddMinus{
    public static void main(String[] args){
        int a = 3;// Define a variable;
        int b = ++a;// Increment operation
        int c = 3;
        int d = --c;// Decrement operation
        System.out.println("Value after increment operation equals " + b);
        System.out.println("Value after decrement operation equals " + d);
    }
}

The output is:

Value after increment operation equals 4
Value after decrement operation equals 2

Explanation:

2. Prefix Increment/Decrement (++a, --a): The increment/decrement operation is performed first, followed by the expression evaluation.

3. Postfix Increment/Decrement (a++, a--): The expression is evaluated first, followed by the increment/decrement operation.

Example:

public class selfAddMinus{
    public static void main(String[] args){
        int a = 5;
        int b = a++; // Postfix increment
        int c = 5;
        int d = ++c; // Prefix increment
        System.out.println("Value after postfix increment equals " + b);
        System.out.println("Value after prefix increment equals " + d);
    }
}

The output is:

Value after postfix increment equals 5
Value after prefix increment equals 6
int a = 5; // Define a variable;
int b = 5;
int x = 2 * ++a;
int y = 2 * b++;
System.out.println("After prefix increment, a=" + a + ", x=" + x);
System.out.println("After postfix increment, b=" + b + ", y=" + y);
}
}

The output is:

After prefix increment, a=6, x=12
After postfix increment, b=6, y=10

Relational Operators

The following table lists relational operators supported by Java.

In the table, integer variable A has a value of 10, and variable B has a value of 20:

Operator Description Example
== Checks if the values of two operands are equal, if yes then the condition becomes true. (A == B) is false.
!= Checks if the values of two operands are equal, if the values are not equal then the condition becomes true. (A != B) is true.
> Checks if the value of the left operand is greater than the value of the right operand, if yes then the condition becomes true. (A > B) is false.
< Checks if the value of the left operand is less than the value of the right operand, if yes then the condition becomes true. (A < B) is true.
>= Checks if the value of the left operand is greater than or equal to the value of the right operand, if yes then the condition becomes true. (A >= B) is false.
<= Checks if the value of the left operand is less than or equal to the value of the right operand, if yes then the condition becomes true. (A <= B) is true.

Example

The following simple example program demonstrates relational operators. Copy and paste the following Java program into a file named Test.java, compile and run this program:

Test.java File Code:

public class Test {

  public static void main(String[] args) {
     int a = 10;
     int b = 20;
     System.out.println("a == b = " + (a == b) );
     System.out.println("a != b = " + (a != b) );
     System.out.println("a > b = " + (a > b) );
     System.out.println("a < b = " + (a < b) );
     System.out.println("b >= a = " + (b >= a) );
     System.out.println("b <= a = " + (b <= a) );
  }
}

The output of the above example is:

a == b = false
a != b = true
a > b = false
a < b = true
b >= a = true
b <= a = false

Bitwise Operators

Java defines bitwise operators, which are applicable to integer types (int), long (long), short (short), character (char), and byte (byte).

Bitwise operators work on bits and perform bit-by-bit operations. Suppose a = 60 and b = 13; their binary representations will be as follows:

A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A | B = 0011 1101
A ^ B = 0011 0001
~A= 1100 0011

The following table lists the basic operations of bitwise operators, assuming integer variable A has a value of 60 and variable B has a value of 13:

Operator Description Example
& If both corresponding bits are 1, the result is 1, otherwise 0 (A & B) results in 12, i.e., 0000 1100
| If both corresponding bits are 0, the result is 0, otherwise 1 (A | B) results in 61, i.e., 0011 1101
^ If the corresponding bits are the same, the result is 0, otherwise 1 (A ^ B) results in 49, i.e., 0011 0001
~ Bitwise complement operator inverts each bit, i.e., 0 becomes 1 and 1 becomes 0 (~A) results in -61, i.e., 1100 0011
<< Left shift operator. The left operand is shifted left by the number of bits specified by the right operand. A << 2 results in 240, i.e., 1111 0000
>> Right shift operator. The left operand is shifted right by the number of bits specified by the right operand. A >> 2 results in 15, i.e., 1111
>>> Zero fill right shift operator. The left operand is shifted right by the number of bits specified by the right operand, and the shifted values are filled up with zeros. A >>> 2 results in 15, i.e., 0000 1111

Example

int a = 60; // 60 = 0011 1100 
int b = 13; // 13 = 0000 1101 
int c = 0;

c = a & b;       // 12 = 0000 1100
System.out.println("a & b = " + c );

c = a | b;       // 61 = 0011 1101
System.out.println("a | b = " + c );

c = a ^ b;       // 49 = 0011 0001
System.out.println("a ^ b = " + c );

c = ~a;          // -61 = 1100 0011
System.out.println("~a = " + c );

c = a << 2;     // 240 = 1111 0000
System.out.println("a << 2 = " + c );

c = a >> 2;     // 15 = 1111
System.out.println("a >> 2  = " + c );

c = a >>> 2;     // 15 = 0000 1111
System.out.println("a >>> 2 = " + c );
}
}

The output is:

a & b = 12
a | b = 61
a ^ b = 49
~a = -61
a << 2 = 240
a >> 2 = 15
a >>> 2 = 15

Below is a simple example program demonstrating bitwise operators. Copy and paste the following Java program, save it as Test.java, and then compile and run the program:

Test.java File Code:

public class Test {
  public static void main(String[] args) {
    int a = 60; /* 60 = 0011 1100 */
    int b = 13; /* 13 = 0000 1101 */
    int c = 0;
    c = a & b;       /* 12 = 0000 1100 */
    System.out.println("a & b = " + c );

    c = a | b;       /* 61 = 0011 1101 */
    System.out.println("a | b = " + c );

    c = a ^ b;       /* 49 = 0011 0001 */
    System.out.println("a ^ b = " + c );

    c = ~a;          /*-61 = 1100 0011 */
    System.out.println("~a = " + c );

    c = a << 2;      /* 240 = 1111 0000 */
    System.out.println("a << 2 = " + c );

    c = a >> 2;      /* 15 = 1111 */
    System.out.println("a >> 2  = " + c );

    c = a >>> 2;     /* 15 = 0000 1111 */
    System.out.println("a >>> 2 = " + c );
  }
}

The compilation and execution result of the above example is as follows:

a & b = 12
a | b = 61
a ^ b = 49
~a = -61
a << 2 = 240
a >> 2  = 15
a >>> 2 = 15

Logical Operators

The table below lists the basic operations of logical operators, assuming boolean variable A is true and variable B is false.

Operator Description Example
&& Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. (A && B) is false.
|| Called Logical OR Operator. If any of the two operands are non-zero, then the condition becomes true. (A || B) is true.
! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A && B) is true.

Example

The following simple example program demonstrates logical operators. Copy and paste the following Java program and save it as Test.java, then compile and run the program:

Example

public class Test {
  public static void main(String[] args) {
    boolean a = true;
    boolean b = false;
    System.out.println("a && b = " + (a&&b));
    System.out.println("a || b = " + (a||b) );
    System.out.println("!(a && b) = " + !(a && b));
  }
}

The compilation and execution result of the above example is as follows:

a && b = false
a || b = true
!(a && b) = true

Short-circuit Logical Operators

When using the AND logical operator, the result is true only if both operands are true. However, if the first operand is false, the result is necessarily false, and the second operand is not evaluated.

Example

public class LuoJi {
  public static void main(String[] args) {
    int a = 5; // Define a variable;
    boolean b = (a&lt;4)&&(a++&lt;10);
    System.out.println("Result of short-circuit logical operator is " + b);
    System.out.println("Value of a is " + a);
  }
}

The execution result is:

Result of short-circuit logical operator is false
Value of a is 5

Analysis: The program uses the short-circuit logical operator (&&). It first evaluates a < 4 as false, so the result of b must be false, and thus it does not proceed to evaluate the second operation a++ < 10, so the value of a remains 5.


Assignment Operators

Below are the assignment operators supported by the Java language:

Operator Description Example
= Simple assignment operator, assigns the value of the right operand to the left operand C = A + B will assign the value of A + B to C
+ = Add and assignment operator, it adds the left operand with the right operand and assigns the result to the left operand C + = A is equivalent to C = C + A
- = Subtract and assignment operator, it subtracts the right operand from the left operand and assigns the result to the left operand C - = A is equivalent to C = C - A
* = Multiply and assignment operator, it multiplies the left operand with the right operand and assigns the result to the left operand C * = A is equivalent to C = C * A
/ = Divide and assignment operator, it divides the left operand by the right operand and assigns the result to the left operand C / = A is equivalent to C = C / A when C and A are of the same type
(%) = Modulus and assignment operator, it takes the modulus of the left operand with the right operand and assigns the result to the left operand C%= A is equivalent to C = C%A
<< = Left shift and assignment operator C << = 2 is equivalent to C = C << 2
>> = Right shift and assignment operator C >> = 2 is equivalent to C = C >> 2
&= Bitwise AND assignment operator C&= 2 is equivalent to C = C&2
^ = Bitwise XOR assignment operator C ^ = 2 is equivalent to C = C ^ 2
| = Bitwise OR assignment operator C | = 2 is equivalent to C = C | 2

Example

The following simple example program demonstrates the assignment operators. Copy and paste the following Java program and save it as Test.java, then compile and run this program:

Test.java File Code:

public class Test {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        int c = 0;
        c = a + b;
        System.out.println("c = a + b = " + c );
        c += a ;
        System.out.println("c += a  = " + c );
        c -= a ;
        System.out.println("c -= a = " + c );
        c *= a ;
        System.out.println("c *= a = " + c );
        a = 10;
        c = 15;
        c /= a ;
        System.out.println("c /= a = " + c );
        a = 10;
        c = 15;
        c %= a ;
        System.out.println("c %= a  = " + c );
        c <<= 2 ;
        System.out.println("c <<= 2 = " + c );
        c >>= 2 ;
        System.out.println("c >>= 2 = " + c );
        c >>= 2 ;
        System.out.println("c >>= 2 = " + c );
        c &= a ;
        System.out.println("c &= a  = " + c );
        c ^= a ;
        System.out.println("c ^= a   = " + c );
        c |= a ;
        System.out.println("c |= a   = " + c );
    }
}

The above example compiles and runs with the following results:

c = a + b = 30
c += a  = 40
c -= a = 30
c *= a = 300
c /= a = 1
c %= a  = 5
c <<= 2 = 20
c >>= 2 = 5
c >>= 2 = 1
c &= a  = 0
c ^= a   = 10
c |= a   = 10

Conditional Operator (?:)

The conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate Boolean expressions. The main purpose of the operator is to decide which value should be assigned to the variable.


variable x = (expression) ? value if true : value if false

Example

Test.java File Code:

public class Test {
   public static void main(String[] args){
      int a, b;
      a = 10;
      // If a equals 1 is true, set b to 20, otherwise set b to 30
      b = (a == 1) ? 20 : 30;
      System.out.println("Value of b is : " + b);

      // If a equals 10 is true, set b to 20, otherwise set b to 30
      b = (a == 10) ? 20 : 30;
      System.out.println("Value of b is : " + b);
   }
}

The above example compiles and runs with the following result:

Value of b is : 30
Value of b is : 20

instanceof Operator

This operator is used to check if an object is an instance of a specific type (class type or interface type).

The instanceof operator is used in the following format:

(Object reference variable) instanceof (class/interface type)

If the object referenced by the variable on the left side of the operator is an instance of the class or interface on the right side, the result is true.

Here is an example:

String name = "James";
boolean result = name instanceof String; // Since name is of type String, it returns true

If the object being compared is compatible with the right-hand type, the operator still returns true.

Consider the following example:

class Vehicle {}

public class Car extends Vehicle {
   public static void main(String[] args){
      Vehicle a = new Car();
      boolean result = a instanceof Car;
      System.out.println(result);
   }
}

The above example compiles and runs with the following result:

true

Java Operator Precedence

When multiple operators appear in an expression, the order of their execution is determined by the precedence of the operators. The precedence of operators can significantly affect the result of an expression.

For example, in the expression (1+3) + (3+2) * 2, if addition is performed first, the result is 18; if multiplication is performed first, the result is 14.

Similarly, in the expression x = 7 + 3 * 2, x gets 13, not 20, because the multiplication operator has higher precedence than the addition operator, so 3 * 2 is calculated first, resulting in 6, and then 7 is added.

The table below lists the operators from highest precedence at the top to lowest at the bottom.

Category Operators Associativity
Postfix () [] . (dot operator) Left to right
Unary expr++ expr-- Left to right
Unary ++expr --expr + - ~ ! Right to left
Multiplicative * / % Left to right
Additive + - Left to right
Shift >> >>> << Left to right
Relational > >= < <= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left
Comma , Left to right

```

❮ Java Abstraction Java Arraylist Retainall ❯