Operators in Java

Operators in Java

In this article, I am going to discuss the Operators in Java. Please read our previous article, where we discussed Type Casting in Java with examples. At the end of this article, you will understand what are Java Operators and when and how to use them Java Application with examples.

What are Java Operators?

An operator in Java is a symbol that is used to perform operations. Operators are the constructs that can manipulate the values of the operands. Consider the expression 2 + 3 = 5, here 2 and 3 are operands and + is called operator. In this article, the goal is to get you the expertise required to get started and work with operators in Java.

What are Java Operators?

There as many types of Operators in Java as follows:

  • Arithmetic Operator
  • Assignment Operator
  • Relational Operator
  • Logical Operator
  • Bitwise Operator
  • Unary Operator
  • Shift Operator
  • Ternary Operator
Arithmetic Operators:

Arithmetic operators are used to performing mathematical operations like addition, subtraction, multiplication, etc. The following table shows the Types of Arithmetic Operators in Java:

Operator Symbol Description Example
Addition Operator + Adds the left operand with the right operand and returns the result. int a=10;

int b=5;

int c = a=b; //15

Subtraction Operator Subtracts the left operand and right operand and returns the result. int a=10;

int b=5;

int c = a-b; //5

Multiplication Operator *  It multiples the left and right operand and returns the result. int a=2;

int b=3;

int c=a*b; //6

Division Operator / Divides the left operand with the right operand and returns the result. int a=10;

int b=5;

int c=a/b; //0

Modulo Operator % Divides the left operand with the right operand and returns the remainder. int a=10;

int b=5;

int c=a/b; //2

Sample Program for Arithmetic Operator:
package Demo;

public class ArithmeticOperator {

 public static void main(String[] args) {
  int A = 10;
                int B = 20;
                System.out.println(A + B);
                System.out.println(A - B);
                System.out.println(A * B);
                System.out.println(A / B);
                System.out.println(A % B);
 }
}

Output:

Arithmetic Operators in Java

Assignment Operators in Java:

The Java assignment operator is used to assign the value on its right to the operand on its left. The following table shows the Types of Assignment Operators in Java.

Symbol Description Example
= Assign the right operand to the left operand.
  1. int a=10;  
  2. int b=20;  
  3. a+=4; //a=a+4 (a=10+4)  
  4. b-=4; //b=b-4 (b=20-4) 
+= Adding left operand with right operand and then assigning it to variable on the left. int a=5;

a += 5; //a=a+5;

-= subtracting left operand with right operand and then assigning it to variable on the left. int a=5;

a -= 5; //a=a-5;

*= multiplying left operand with right operand and then assigning it to the variable on the left. int a=5;

a *= 5; //a=a*5;

/= dividing left operand with right operand and then assigning it to variable on the left. int a=5;

a /= 5; //a=a/5;

%=  assigning modulo of left operand with right operand and then assigning it to the variable on the left. int a=5;

a /= 5; //a=a/5;

Sample Program for Assignment Operators:
package Demo;

public class AssignmentOperator {

 public static void main(String[] args) {
   int a = 10;
         int b=20;
         int c;
         System.out.println(c = a); // Output =10
         System.out.println(b += a);// Output=30
         System.out.println(b -= a);// Output=20
         System.out.println(b *= a);// Output=200
         System.out.println(b /= a);// Output=2
         System.out.println(b %= a);// Output=0
         System.out.println(b ^= a);// Output=0

 }
}

Output :

Assignment Operators in Java

Relational Operators in Java:

The Relational Operators are also known as Comparison Operators. It determines the relationship between two operands and returns the Boolean results, i.e. true or false after the comparison. The following table shows the Types of Relational Operators in Java.

Operator Symbol Description Example
Equal to == returns true of the left-hand side is equal to the right-hand side. 5==3 is evaluated to false.
Not Equal to != returns true of the left-hand side is not equal to the right-hand side. 5!=3 is evaluated to true.
Less than < returns true of the left-hand side is less than the right-hand side. 5<3 is evaluated to false
Less than or equal to <=  returns true of the left-hand side is less than or equal to the right-hand side. 5<=5 is evaluated to true
Greater than > returns true of the left-hand side is greater than the right-hand side. 5>3 is evaluated to true
Greater than or Equal to >= returns true of the left-hand side is greater than or equal to the right-hand side. 5>=5 is evaluated to true
Instance of Operator instanceOf It compares an object to a specified type. String test = “asdf”;

boolean result;

result = test instanceOf String; //true

Sample Program for Relational Operator :
package Demo;

public class RelationalOperator {

 public static void main(String[] args) {
  int a = 10;
        int b=20;
        System.out.println(a == b); // returns false because 10 is not equal to 20
        System.out.println(a != b); // returns true because 10 is not equal to 20
        System.out.println(a > b); // returns false 
        System.out.println(a < b); // returns true 
        System.out.println(a >= b); // returns false
        System.out.println(a <= b); // returns true

 }
}

Output:

Relational Operators in Java

Logical Operators in Java:

The Logical Operators are mainly used in conditional statements and loops for evaluating a condition. They are basically used with binary numbers. The following table shows the types of Logical Operators in Java.

Operator Symbol Description Example
Logical OR || It returns true if either of the Boolean Expression is true. false || true is evaluated to true
Logical AND && It returns true if all the Boolean Expressions are true false && true is evaluated to false.
Sample Program for Logical Operators:
package Demo;

public class LogicalOperators {

 public static void main(String[] args) {
        int a = 10;
        System.out.println(a<10 & a<20);  //returns false
        System.out.println(a<10 || a<20); //returns true
        System.out.println(!(a<10 &  a<20)); //returns true

 }
}

Output:

Logical Operators in Java

Java Bitwise Operators:

The Bitwise operator performs bit by bit processing. They can be used with any of the integer types. The following table shows the Types of Bitwise Operators in Java.

Operator Symbol Description Example
Bitwise OR | It compares corresponding bits of two operands. If either of the bits is 1, it gives 1. If not, it gives 0. int a=12, b=25;

int result = a|b; //29

Bitwise AND & It compares corresponding bits of two operands. If either of the bits is 1, it gives 1. If either of the bits is not 1, it gives 0. int a=12, b=25;

int result = a&b; //8

Bitwise XOR ^ It compares corresponding bits of two operands. If corresponding bits are different, it gives 1. If corresponding bits are the same, it gives 0. int a=12, b=25;

int result = a^b; //21

Bitwise Complement ~ It inverts the bit pattern. It makes every 1 to 0 and every 0 to 1. int a=35;

int result = ~a; //-36

Sample Program for Bitwise Operators:
package Demo;

public class BitwiseOperators {

 public static void main(String[] args) {
   int a = 58; //111010
         int b=13; //1101
         System.out.println(a&b);  //returns 8 = 1000
         System.out.println(a|b);  //63=111111
         System.out.println(a^b);  //55=11011
         System.out.println(~a);  //-59

 }
}

Output:

Java Bitwise Operators

Unary Operators in Java:

The Unary operators need only one operand. They are used to increment, decrement, or negate a value. The following table shows the Types of Unary Operators in Java.

Operator Symbol Description Example
Unary minus It is used for negating the values. int a=5.2;

int b = -a; //-5.2

Unary plus + It is used for giving positive values. int a=5.2;

int b = +a; //5.2

Increment Operator ++ It is used for incrementing the value by 1. int a=5.2;

int b = ++a; //6.2

Decrement Operator It is used for decrementing the value by 1. int a=5.2;

int b = –a; //4.2

Logical NOT Operator ! It is used for inverting a Boolean value boolean a=false;

boolean b=!a; //true

Note: There is basically two types of Increment Operator:

Post Increment Operator:

Value is first used for computing the result and then incremented.
Example:

int b = 10, c = 0;
// c=b then b=b+1
c=b++;
System.out.println(“Value of c (b++) = “ +c);

Output: Value of c (b++) = 10

Pre Increment Operator:

Value is incremented first and then result is computed.
Example:

int a = 20, c = 0;
// a = a+1 and then c = a;
c=++a;
System.out.println(“Value of c (++a) = “ +c);

Output: Value of c (++a) = 21

Note: There are basically two types of Decrement Operator:

Post Decrement Operator:

Value is first used for computing the result and then decremented.
Example:

int e = 40, c = 0;
// c=e then e=e-1
c=e–;
System.out.println(“Value of c (e–) = “ +c);

Output: Value of c (e–) = 40

Pre Decrement Operator:

Value is decremented first and then result is computed.
Example:

int d = 20, c = 0;
// d=d-1 then c=d
c=–d;
System.out.println(“Value of c (–d) = “ +c);

Output: Value of c (–d) = 19

Sample Program for Unary Operator :
package Demo;

public class UnaryOperator {

 public static void main(String[] args) {
  int a = 10;
        boolean b=true;
        System.out.println(a++);  //returns 11
        System.out.println(++a);  
        System.out.println(a--);  
        System.out.println(--a);  
        System.out.println(!b); // returns false

 }
}

Output:

Unary Operators in Java

Shift Operator in Java:

The shift operator is used when you’re performing logical bits operations, as opposed to mathematical operations. These operators are used to shift the bits of a number left or right thereby multiplying or dividing the number by two respectively. They can be used when we have to multiply or divide a number by two. 

Types of Shift Operator:

Operator Symbol Description Example
Left Shift Operator << It is used to shift all of the bits in value to the left side of a specified number of times. 10<<2 //10*2^2=10*4=40
Right Shift Operator >> It is used to move left operands value to right by the number of bits specified by the right operand. 10>>2 //10/2^2=10/4=2 
Sample Program for Shift Operators:
package Demo;

public class ShiftOperators {

 public static void main(String[] args) {
  int a=58; 
        System.out.println(a<<2); //232=11101000 
        System.out.println(a>>2);  //returns 14=1110
        System.out.println(a>>>2); //returns 14

 }
}

Output:

Shift Operator in Java

Ternary Operator in Java:

The Ternary Operator is also known as the Conditional Operator. It is the shorthand of the if-else statement. It is the one-liner replacement of the if-else statement in Java. It is called ternary because it has three operands. The general format of the ternary operator is: Condition ? if true : if false

The above statement means that if the condition evaluates to true, then execute the statements after the ‘?’ else execute the statements after the ‘:’.

Example:

int a=2;  
int b=5;  
int c = (a<b)?a:b; 

Output: 2

Sample Program for Ternary Operators:
package Demo;

public class TernaryOperators {

 public static void main(String[] args) {
        int a = 20, b = 10, c = 30, res; 
        res = ((a > b) ? (a > c)? a: c: (b > c)? b: c); 
        System.out.println("Max of three numbers = "+ res); 

 }
}

Output:

Ternary Operator in Java

Java Operator Precedence and Associativity

Java has well-defined rules for specifying the order in which the operators in an expression are evaluated when the expression has several operators. For example, multiplication and division have higher precedence than addition and subtraction. Precedence rules can be overridden by explicit parentheses.

Precedence and associative rules are used when dealing with hybrid equations involving more than one type of operator. In such cases, these rules determine which part of the equation to consider first as there can be many different valuations for the same equation.

Precedence order:

When two operators share an operand the operator with the higher precedence goes first. For example, 1 + 2 * 3 is treated as 1 + (2 * 3), whereas 1 * 2 + 3 is treated as (1 * 2) + 3 since multiplication has a higher precedence than addition.

Associativity:

When an expression has two operators with the same precedence, the expression is evaluated according to its associativity. For example x = y = z = 17 is treated as x = (y = (z = 17)), leaving all three variables with the value 17, since the = operator has right-to-left associativity (and an assignment statement evaluates to the value on the right hand side). On the other hand, 72 / 2 / 3 is treated as (72 / 2) / 3 since the / operator has left-to-right associativity. Some operators are not associative: for example, the expressions (x <= y <= z) and x++– are invalid.

The table below shows all Java operators from highest to lowest precedence, along with their associativity.

Level Operator Description Associativity
16 []
.
()
access array element
access object member
parentheses
left to right
15 ++
unary post-increment
unary post-decrement
not associative
14 ++

+

!
~
unary pre-increment
unary pre-decrement
unary plus
unary minus
unary logical NOT
unary bitwise NOT
right to left
13 ()
new
cast
object creation
right to left
12 * / % multiplicative left to right
11 + –
+
additive
string concatenation
left to right
10 << >>
>>>
shift left to right
9 < <=
> >=
instanceof
relational not associative
8 ==
!=
equality left to right
7 & bitwise AND left to right
6 ^ bitwise XOR left to right
5 | bitwise OR left to right
4 && logical AND left to right
3 || logical OR left to right
2 ?: ternary right to left
1  =   +=   -=
*=   /=   %=
&=   ^=   |=
<<=  >>= >>>=
assignment right to left

Note: Larger the number means higher the precedence.

In the next article, I am going to discuss Variables in Java with examples. Here, in this article, I try to explain Java Operators in detail. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *