Pre & Post increment operator example Java

Hi,

Today we will be Finding the difference between pre- and post- increment of variables.

Pre -increment Operator:

```int x=1; System.out.println("x:"+x); System.out.println("x:"+(++x)); System.out.println("x:"+x); ```

Post -increment Operator:

```int x=1; System.out.println("x:"+x); System.out.println("x:"+x++); System.out.println("x:"+x); ```

So what will be output you think??

For Post – increment Operator:

Output:

``` x:1 x:1 x:2 ```

For Pre -increment Operator:
Output:
``` x:1 x:2 x:2 ```

Explanation:

For pre – increment operator :

System.out.println(“x:”+x);  //Display value of x i.e 1

System.out.println(“x:”+(++x));  //First increase the value of x and then display i.e 2

System.out.println(“”x:”+x);  //Display value of x i.e 2

For post -increment operator :

System.out.println(“x:”+x);  //Display value of x i.e 1

System.out.println(“x:”+(x++));  //First display the value of x and then increment i.e 1

System.out.println(“”x:”+x);  //Display the incremented value of x i.e 2

That’s it so simple of Pre increment and Post increment Operation in Java.

Note: The operator (++) is called as Increment Operator and (–) is called as Decrement operator and these both Operator fall under the category of Unary Operator.

Feel free to comment 🙂