Tutorials

Java Operators


Increment Decrement Operator


Increment operators and decrement operators requires only one operand thus are known as Unary operators.

They are most frequently used in for and loops to increment or decrement the value of the variable after every loop.

 

Increment Operator (++)

Increment operator increases the value stored in the variable by one. 

Increment operator is denoted by ++. 

Example, a++; x++, etc. 

 

The given statements are all equivalent. 

  • i++;
  • i = i + 1;
  • i += 1;

All increase the value of variable i by 1.

 

Increment operator can be used in two forms with variables:

  1. pre-increment →  ++i  : This operator will first perform increment operation and then assign the incremented value.
  2. post-increment  i++  : This operator will first assign the value and then perform increment operation.

Example 1: Post-increment example


int i = 1; 
int j = i++;

System.out.println("i="+ i + "j="+ j);

OUTPUT

i=2  j=1

 

How the above code works?

  • value of i=1
  • i++ (post-increment) form is assigned to i.
  • We already know that post-increment operator will first assign the value and then perform increment operation.
  • Thus value of i=1, is first asigned to j and then increment operation is performed on variable i.
  • Hence we get i=2 and j=1

Example 2: Pre-increment example


int i = 1; 
int j = ++i;

System.out.println("i="+ i + "j="+ j);

OUTPUT

i=2  j=2

 

How the above code works?

  • value of i=1
  • ++i (pre-increment) form is assigned to i.
  • We already know that pre-increment operator will first perform increment operation and then assign the incremented value.
  • Thus value of i=1, is first incremented by 1, i.e i=2 and then value is assigned to j.
  • Hence we get i=2 and j=2

Decrement Operator (--)

Decrement operator decreases the value stored in the variable by one. 

Decrement operator is denoted by --. 

Example, a--; x--, etc. 

 

The given statements are all equivalent. 

  • i--;
  • i = i - 1;
  • i - = 1;

All decrease the value of variable i by 1.

 

Decrement operator can be used in two forms with variables:

  1. pre-decrement →  --i  : This operator will first perform decrement operation and then assign the decremented value.
  2. post-decrement  i--  : This operator will first assign the value and then perform decrement operation.

Try the example given in increment operator. Replace the ++ with -- and see how it works.

Things will work in similar manner except decrement operator will decrease the value instead of increasing.



Please Share this page
Views : 116
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!