Post-increment VS Pre-increment in Java

Hello everyone! learn the concept of post-increment and pre-increment with a detailed explanation in Java. We know the concept of increment. The increment is adding one to the current value. We all have a little confusion about post-increment and pre-increment. Now let us get over this confusion with a detailed explanation. I hope this will help you to understand the difference between post-increment and pre-increment in Java.

Post-Increment VS Pre-Increment in Java

Post-increment: In this concept, value is first computed whatever the operation it might be and then the computed value is incremented. So, first it will perform the operation and the result obtained will be incremented by one.

public class Main {
  public static void main(String[] args) {
  int x=10;
  int y=x++;
  System.out.println(y);
  System.out.println(x);
    
  }

}

Output:10

11

From the above program, first the value of x is assigned to y and then its incremented value is stored in x. As per the definition, the output is clear.

Post-increment: In this concept, value is first incremented and then it will perform whatever the operation it might be. So first, it will increment by one and perform its respective operations.

public class s {
  public static void main(String[] args) {
  int x=10;
  int y=++x;
  System.out.println(y);
  System.out.println(x);
    
  }

}

Output: 11

11

From the above program, first the value is incremented and its incremented value is assigned to x. As per the definition, the output is clear.

Hope the explanation is clear. And some important points to mention over here, We cannot use increment operator to boolean variables. And we cannot use these operators to final variables since the value assigned to the final variable is fixed we cannot add or subtract and alter its value.

Also read:

Leave a Reply

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