Operators in Java


JavaViews 4102

An operator in Java is a symbol with which we can perform operations on the operand. An operand may be a variable or a value. For any operation, we must have a minimum of 1 operand.

Types of Operators in Java

Below are the different types of Operators in Java

Operators in Java

Arithmetic Operators in Java

We use Arithmetic operators in Java to perform Arithmetic operations like addition, subtraction, multiplication, division. To perform all these operations, we require 2 operands on either side of the operator.

OperatorOperationSyntax
+Additiona+b
-Subtractiona-b
*Multiplicationa*b
/Divisiona/b
%Modulo - To find the remindera%b

Arithmetic Operator Example

In the below example, we can see that in every expression we use 2 operands to perform arithmetic operations. In this case, a and b are called operands and the symbol between the operands is the operator.

public class ArithmeticOperators {

  public static void main(String[] args) {
    int a = 10;
    int b = 20;
    int sum = a + b;
    System.out.println("Sum of a and b is: " + sum);
    
    int diff = b - a;
    System.out.println("Difference between a and b is: " + diff);
    
    int prod = a * b;
    System.out.println("Product of a and b is: " + prod);
    
    int div = b/a;
    System.out.println("Division of a and b is: " + div);
    
    int mod = b%a;
    System.out.println("Reminder of a and b is: " + mod);

  }

}
Sum of a and b is: 30
Difference between a and b is: 10
Product of a and b is: 200
Division of a and b is: 2
Reminder of a and b is: 0

Unary Operators in Java

This is also another type of arithmetic operator but requires only 1 operand to perform the operation. Hence its name is Unary operator. This is mainly used for postfix and prefix operator evaluation. We use it to increment, decrement a value, or negate an expression or invert a boolean value.

SyntaxOperator typeOperation
expr++PostfixIncreases the value by 1 after the value is assigned
expr--PostfixDecreases the value by 1 after the value is assigned
++exprPrefixIncreases the value by 1 before the value is assigned
--exprPrefixDecreases the value by 1 before the value is assigned
+exprPrefixDisplays expression in positive
-exprPrefixDisplays expression in negative
!exprPrefixInverts the value of expression

Unary Operator Example

Let’s understand the unary operators more clearly with the below example. When we execute the expression a++ the value of a is still 5 and prints the result as 5 and then increments the value to 6 internally. Hence the first output is 5.

Now, when we execute a–, from previous expression value of a is 6, hence it prints 6 and the decrements the value to 5 internally. Hence the second output is 6.

Next, we execute –a, which means before it prints it decrements the value by 1 i.e (5-1), Hence the third output is 4.

When we execute ++a, the value first increments by 1 and then prints the output as 5 i.e(4+1).

public class UnaryOperator {

  public static void main(String[] args) {
    int a = 5;
    
    System.out.println("Postfix increment:");
    System.out.println(a++);
    System.out.println("Postfix decrement:");
    System.out.println(a--);
    System.out.println("Prefix decrement:");
    System.out.println(--a);
    System.out.println("Prefix increment:");
    System.out.println(++a);
    
  }
}
Postfix increment:
5
Postfix decrement:
6
Prefix decrement:
4
Prefix increment:
5

Next, let’s see how + and unary operator works. + gives a positive value if the value is already positive. If the value is negative, it gives a negative value since + and – results in a -. Hence the 1st output is 60 for +b i.e +(+60) = 60 and 2nd output is -55 for +a which means +(-55) = -55.

Similarily, – gives a negative integer value if the value is positive and gives a positive integer if the value is negative. Hence the output is -55 for -b i.e -(60) = -60 and 55 for -a which means -(-55) = 55.

! (NOT) operator reverses the boolean value. If the value is true, it returns false and if it’s false it returns true.

public class UnaryOperator {

  public static void main(String[] args) {
    int a = -55;
    int b = 60;
    Boolean value = false;
    System.out.println("Positive value:");
    System.out.println(+b);
    System.out.println(+a);
    System.out.println("Negative value:");
    System.out.println(-b);
    System.out.println(-a);
    System.out.println("Invert value:");
    System.out.println(!value);
    
  }
}
Positive value:
60
-55
Negative value:
-60
55
Invert value:
true

Logical Operators in Java

We use logical operators to evaluate a condition or expression. It may be a single or multiple expression.

OperatorOperationSyntax
&&Returns true if both expressions are true(a>b)&&(b<c) where a>b is expression1 and b<c is expression2
||Returns true if any one expression is true(a>b) || (b<c) where a>b is expression1 and b<c is expression2
!Reverses the result. Returns true if the expression is false and vice versa!(a>b)

Logical Operator Example

Logical AND returns true only if both the expression values are true. Since the 1st expression (a>10) is false and 2nd expression (b<20) is true, false AND true returns false as output.

Logical OR returns true is any one of the expression value is true. Here, the output is true since false OR true returns true.

Logical NOT reverse the boolean value. If the value is false it gives true and vice versa.

public class LogicalOperator {

  public static void main(String[] args) {
    int a = 5;
    int b = 10;
    Boolean c = (a>10 && b<20 );
    System.out.println("Output of Logical AND: " + c);
    Boolean d = (a>10 || b<20);
    System.out.println("Output of Logical OR: " + d);
    System.out.println("Output of Logical NOT: " + !d);
    
  }

}
Output of Logical AND: false
Output of Logical OR: true
Output of Logical NOT: false

Relational Operators in Java

When we want to compare two variables or expressions, then we use relational or comparison operators in Java. We mainly use this in evaluating if-else conditions which we will learn in later tutorials.

OperatorOperationSyntax
==Checks if both variables/expressions are equala==b
!=Checks if the variables/expressions are not equal to each othera!=b
>Checks which variable or expression is greatera>b
<Checks which variable or expression is lessera<b
>=Checks which variable or expression is greater than or equal to the othera>=b
<=Checks which variable or expression is lesser than or equal to the othera<=b

Relational Operator Example

This example shows you how to use relational operators. Here, we are using comparison operators for expression in if-else statements. If the condition is true if statement will be executed. If the condition is false, else statement will be executed.

public class RelationalOperator {

  public static void main(String[] args) {
    int a = 10;
    int b = 20;
    if(a==b)
      System.out.println("a and b are equal");
    else
      System.out.println("a and b are not equal");
    if(a>b)
      System.out.println("a is greater than b");
    else
      System.out.println("b is greater than a");
    if(a<b)
      System.out.println("a is lesser than b");
    else
      System.out.println("b is lesser than a");
    if(a!=b)
      System.out.println("a is not equal to b");
    else
      System.out.println("a is equal to b");
    if(a>=b)
      System.out.println("a is greater than or equal to b");
    else
      System.out.println("a is not greater than or equal to b");
    if(a<=b)
      System.out.println("a is lesser than or equal to b");
    else
      System.out.println("a is not lesser than or equal to b");
  }

}
a and b are not equal
b is greater than a
a is lesser than b
a is not equal to b
a is not greater than or equal to b
a is lesser than or equal to b

Bitwise Operators in Java

These operators perform bit by bit operation. The output is either 1 or 0 based on the comparison.

OperatorOperation
&AND - Returns 1 if both bits are 1
|OR - Returns 1 if any one bit is 1
^NOT - Inverts the bit
~XOR(Exclusive OR) - Returns 1 if only one of the two bits is 1
<<Shifts left by pushing the bits from right to left and fills with 0 in the end by removing the left most bit
>>Shifts right by pushing the copies of the leftmost bit and removes the rightmost bit
>>>Shifts right by pushing 0 from left and removes the rightmost bit

Bitwise Operator Example

When we use bitwise operators, the calculation is done by converting the integer to a binary value. Let’s understand this in detail with an example below.

Bitwise AND operator returns 1 if only if both the bits are 1. Hence the below output displays 0 since this condition is not met.

Bitwise OR operator returns 1 if any 1 of the bit is 1. Hence the below output is 7 whose binary value is 0111.

Bitwise Operator

Bitwise XOR operator inverts every bit as you can see in the below illustration.

Bitwise Operator

The left Shift operator shifts the bit from right to left by removing the leftmost bit and adds 0 to the rightmost bit. The number of bits is moved based on the expression. In the below example, the bits are moved by 1 position.

Bitwise Operator

Another way to calculate the left-shift operator is as below. Multiply the integer value with power raised to 2 based on the number of bits.

a=5

a<<1 -> 5*2^1  = 5*2=10

a<<2 -> 5*2^2 = 5*4 = 20

The Right Shift operator shifts the bit from left to right by removing the rightmost bit and adds 0 to the leftmost bit.

Another way to calculate the right-shift operator is as below. Divide the integer value with power raised to 2 based on the number of bits.

a=5

a>>1 -> 5/2^1 = 5/2 = 2

a>>2 -> 5/2^2 = 5/4 = 1

public class BitwiseOperator {

  public static void main(String[] args) {
    int a = 5;
    int b = 2;
    int val;
    
    val = a&b;
    System.out.println("Output of Bitwise AND: "+ val);
    
    val = a|b;
    System.out.println("Output of Bitwise OR: " + val);
    
    System.out.println("Output of Bitwise XOR: " + ~a);
    System.out.println("Output of RightShift: " + (a>>1));
    System.out.println("Output of LeftShift: " + (a<<1));
    System.out.println("Output of RightShift with 0: " + (a>>>1));
    
  }

}
Output of Bitwise AND: 0
Output of Bitwise OR: 7
Output of Bitwise XOR: -6
Output of RightShift: 2
Output of LeftShift: 10
Output of RightShift with 0: 2

Assignment Operators in Java

This Operator is used in assigning value to a variable based on the required operation.

OperatorOperationSyntax
=Assigns value from right operand to left operanda=b
+=Add and assigns the result value to the left operanda+=b is same as
a=a+b
-=Subtracts and assigns the result value to the left operanda-=b is same as
a=a-b
*=Multiplies and assigns the result value to the left operanda*=b is same as
a=a*b
/=Divides and assigns the result value to the left operanda/=b is same as
a=a/b
%=Performs modulo operation and assigns the result value to the left operanda%=b is same as
a=a%b
&=Performs Bitwise AND operation and assigns the result value to the left operanda&=b is same as
a=a&b
|=Performs Bitwise OR operation and assigns the result value to the left operanda|=b is same as
a=a|b
^=Performs Bitwise exclusice OR operation and assigns the result value to the left operanda^=b is same as
a=a^b
>>=Performs Left shift operation and assigns the result value to the left operanda>>=b is same as
a=a>>b
<<=Performs Right shift operation and assigns the result value to the left operanda<<=b is same as
a=a<<b

Assignment Operator Example

In the below example, we can see how to use various assignment operators.

public class AssignmentOperaor {

  public static void main(String[] args) {
    int x = 5;
    int y = 10;
    int i = 3;
    int j = 2;
    int a;
    a=x;
    System.out.println("a=x: " + a);
    x+=5;
    System.out.println("x=x+5: " + x);
    y-=2;
    System.out.println("y=y-2: " + y);
    x*=4;
    System.out.println("x=x*4: " + x);
    y/=2;
    System.out.println("y=y/2: " + y);
    a%=5;
    System.out.println("a=a%5: " + a);
    System.out.println("i=i&j: " + (i&=j));
    System.out.println("i=i|j: " + (i|=j));

  }

}
a=x: 5
x=x+5: 10
y=y-2: 8
x=x*4: 40
y=y/2: 4
a=a%5: 0
i=i&j: 2
i=i|j: 2

Ternary Operators in Java

This operator displays the result based on the condition. The condition is an expression that returns a boolean value.

Syntax

var1 = (expression1) ? value1 : value2

var1 is the variable which holds the result of the operation

expression1 is the expression that evaluates a condition

value1 – Assigns this value as a result to the variable if the expression returns true

value2 – Assigns this value as a result to the variable if the expression returns false

In other words, if the expression is true, the variable holds value1 else holds value2

Ternary Operator Example

In the first statement, the output is 100 since the expression returns true and in the 2nd statement, the output is 50 since the expression is false.

public class TernaryOperator {

  public static void main(String[] args) {
    int value;
    int x = 150;
    int y = 100;
    value = (x!=y) ? 100:50;
    System.out.println(value);
    
    value = (x<y) ? 100:50;
    System.out.println(value);
  }

}
100
50

InstanceOf operator

This is a special operator that checks whether an object belongs to a specific type. Let’s see an example below to understand this better.

public class SpecialOperator {

  public static void main(String[] args) {
    String value = "Welcome to Java tutorial";
    Boolean b;
    b = (value instanceof String);
    System.out.println(b);
  }

}
true

Below is another example of instanceof operator when we have an extended class. Here d is an object of the class Department. But Department class extends College class. Hence d is an instanceof both the class and that’s why we get true as output for both the conditions.

public class Department extends College {

  public static void main(String[] args) {
    Department d = new Department();
    Boolean b;
    b = (d instanceof College);
    System.out.println(b);
    b = (d instanceof Department);
    System.out.println(b);
  }

}
true
true

When a variable does not have any value assigned which means when it is null, instanceof returns false instead of true.

public class SpecialOperator {

  public static void main(String[] args) {
    String value = null;
    Boolean b;
    b = (value instanceof String);
    System.out.println(b);
  }

}
false

Precedence Of Operators

It is important to understand the precedence of operators when an expression has more than 1 operator. Java evaluates the expression based on the below precedence which shows from high to low.

Operator TypeOperators
Unary operator++(postfix)

— (postfix)

++(prefix)

–(prefix)

+

!

~

Multiplicative operator*, /, %
Additive operator+, –
Shift operator<<

>>

>>>

Relational operator>

>=

<

<=

Equality operator==

!=

Bitwise Operator&, ^, |
Logical Operator&&

||

Ternary Operator?:
Assignment Operator=, +=, -=, *=, /=, %=

>, >=, <, <=

&=, ^=, |=

Example Program

In the below example, ++ takes the higher precedence, followed by * and then -. Hence we evaluate the expression as below.

++b = 5+1 = 6

++b*c = 6*2 = 12

a-(++b*c) = 15-12 = 3 which is the final output

public class OperatorPrecedence {

  public static void main(String[] args) {
    int a = 15;
    int b = 5;
    int c = 2;
    int result;
    result = (a-++b*c);
    System.out.println(result);

  }

}
3

Reference

Translate »