Java Operators

Java operators are symbols which are used to perform operations. For example addition, subtraction, division, multiplication, remainder etc. We can divide the Java operators into the following groups

Unary Operator
Arithmetic Operator
Shift Operator
Relational Operator
Bitwise Operator
Logical Operator
Ternary Operator
Assignment Operator

Java Unary Operators

The Java unary operators needs only one operand. Unary operators are used to perform many operations e.g.
Increment /decrement a number
negating an expression
inverting the value of a boolean

Java Unary Operator Increment (++) / Decrement (–) Example


class OperatorIncrementDecrementExample{
public static void main(String args[]){
int x=50;
System.out.println(x++);//Now value in x is 51
System.out.println(++x);//52
System.out.println(x--);//51
System.out.println(--x);//50
}}

Java Arithmetic Operators

To perform addition, subtraction, multiplication, and division java arithmetic operators are used. They work as basic mathematical operators.

Java Arithmetic Operators Example:


class OperatorArithmeticExample{
public static void main(String args[]){
int a1=100;
int b1=50;
System.out.println(a1+b1);//150
System.out.println(a1-b1);//50
System.out.println(a1*b1);//5000
System.out.println(a1/b1);//2
System.out.println(a1%b1);//0
}}

Java Shift Operators

There are two shift operators in java i.e. left shift operator and right shift operator

Java left shift operator

‘<<‘ is used as left shift operator in java to shift all of the bits in a value to the left side of a specified number of times.
Examples:

class JavaLeftShiftExample{
public static void main(String args[]){
System.out.println(10<<1);//10*2^1=10*2=20 (i.e. shift left by 21)
System.out.println(10<<3);//10*2^3=10*8=80 (i.e. shift left by 23)
}
}

Java Right Shift Operator

‘>>’ is used as right shift operator to move left operands value to right by the number of bits specified by the right operand.
Example:

class RightShiftExample{
public static void main(String args[]){
System.out.println(10>>2);//10/2^2=10/4=2 (i.e shift right by 22)
System.out.println(40>>3);//40/2^3=40/8=5 (i.e. shift right by 23)
}
}