Monday 2 May 2016

Difference between i++ and ++i in java

Lets take, int i = 100;

Keep track on the values of i and x...

And now try to concentrate on the difference between i++ (post increment) and ++i (pre-increment),

Post increment

int x = i++;
Here value of i will first be assigned to the variable x and then its original value will be incremented. That's why its referred to as post increment operation which means do the task first and then increment.

So, x = 100, because value of i is assigned to x first and then i++ happens and the value of i is incremented by 1. Thus i = 101.


Preincrement

int x = ++i;
Here value of i will first be incremented by 1 and then the incremented value will be assigned to x.
That's why its referred to as pre-increment operation which means increment the value first and then perform the task with incremented value.

So, x = 101, because the value of i is incremented first and then assigned to x.
And obviously, i = 101.

Go through the example to develop better understanding :

Find the value of x when i = 1;

1)             int i = 1;
int x = i++;    // here value of, x = 1 and i = 2

int y = ++i;    // Now value of i=2 so ++i will increment the i(=3) by 1 and assign it to y(=3)
        System.out.println("Value of x = "+ x);
        System.out.println("Value of y = "+ y);

OUTPUT :
Value of x = 1
Value of y = 3


Sample code:

SourcePrePostIncrementOperator.java


package basic;

public class PrePostIncrementOperator {

      public static void main(String[] args) {
            int i = 0, j=0;
            int x = i++;  //Here i=1 but x=o(initial value of i)
            System.out.println("x: "+ x +" i: "+ i); 
           
            int y = ++j;
            System.out.println("y: "+ y +" j: "+j);
      }

}


OUTPUT:
x: 0 i: 1
y: 1 j: 1


So in both the case we see that value of the variable(i&j) is getting incremented. The difference is in the process of assigning the value.
i++ assigns non-incremented value to x. whereas
++j assigns the incremented value to y.

Hope I have been able to explain the concept clearly to you. Whats your thought or query about the topic? 

Please write it in the comment box.

No comments:

Post a Comment

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.