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 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s