Explain Increment and Decrement operators with example.


Operators in Java

Operator in Java is a symbol which is used to perform operations. For example: +, -, *, / etc.

There are many types of operators in Java which are given below:

  • Unary Operator,
  • Arithmetic Operator,
  • Shift Operator,
  • Relational Operator,
  • Bitwise Operator,
  • Logical Operator,
  • Ternary Operator and
  • Assignment Operator.

Java Operator Precedence

Operator TypeCategoryPrecedence
Unarypostfixexpr++ expr--
prefix++expr --expr +expr -expr ~ !
Arithmeticmultiplicative* / %
additive+ -
Shiftshift<< >> >>>
Relationalcomparison< > <= >= instanceof
equality== !=
Bitwisebitwise AND&
bitwise exclusive OR^
bitwise inclusive OR|
Logicallogical AND&&
logical OR||
Ternaryternary? :
Assignmentassignment= += -= *= /= %= &= ^= |= <<= >>= >>>=

Java Unary Operator

The Java unary operators require only one operand. Unary operators are used to perform various operations i.e.:

  • incrementing/decrementing a value by one
  • negating an expression
  • inverting the value of a boolean

Java Unary Operator Example: ++ and --

  1. class OperatorExample{  
  2. public static void main(String args[]){  
  3. int x=10;  
  4. System.out.println(x++);//10 (11)  
  5. System.out.println(++x);//12  
  6. System.out.println(x--);//12 (11)  
  7. System.out.println(--x);//10  
  8. }}  

Output:

10
12
12
10

Java Unary Operator Example 2: ++ and --

  1. class OperatorExample{  
  2. public static void main(String args[]){  
  3. int a=10;  
  4. int b=10;  
  5. System.out.println(a++ + ++a);//10+12=22  
  6. System.out.println(b++ + b++);//10+11=21  
  7.   
  8. }}  

Output:

22
21

Java Unary Operator Example: ~ and !

  1. class OperatorExample{  
  2. public static void main(String args[]){  
  3. int a=10;  
  4. int b=-10;  
  5. boolean c=true;  
  6. boolean d=false;  
  7. System.out.println(~a);//-11 (minus of total positive value which starts from 0)  
  8. System.out.println(~b);//9 (positive of total minus, positive starts from 0)  
  9. System.out.println(!c);//false (opposite of boolean value)  
  10. System.out.println(!d);//true  
  11. }}  

Output:

-11
9
false
true