Differentiate between the prefix and postfix forms of the ++ operator in java?


Java provides two operators namely ++ and --, to increment and decrement values by 1 respectively.

There are two variants of these operators −

Pre-increment/decrement − This form, increments/decrements the value first, and then performs the specified operation.

Example

In the following example, the initial value of the variable i is 5. We are printing the incremented value of it using the pre increment operator.

Since we are using the pre increment operator, the value of i is incremented then printed.

 Live Demo

public class ForLoopExample {
   public static void main(String args[]) {
      int i = 5;
      System.out.println(++i);
      System.out.println(i);
   }
}

Output

6

Post-increment/decrement − This form, performs the specified operation first, and then increments/decrements the value.

Example

In the following example, the initial value of the variable i is 5. We are printing the incremented value of it using the post increment operator and, we are printing the i value again.

Since we are using the post increment operator, the value of i is printed and then incremented.

 Live Demo

public class ForLoopExample {
   public static void main(String args[]) {
      int i = 5;
      System.out.println(i++);
      System.out.println(i);
   }
}

Output

5
6

Example

 Live Demo

public class ForLoopExample {
   public static void main(String args[]) {
      int i = 5;
      System.out.println(i--);
      System.out.println(i);
      int j =5;
      System.out.println(--j);
   }
}

Output

5
4
4

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements