Wednesday, May 24, 2006

common mistake between (++j) & (j++)

Following is the example;

example 1:

int i = 4;
int j = 6;

int k = ++i + j;
System.out.println(k);

The output of above will be 11. That is, it first increments the value of i by 1 and then adds to j. Now consider the following example -

example 2:

int i = 4;
int j = 6;

int k = i++ + j;
System.out.println(k);

The output of above will be 10. Because, first it adds up the value of i & j and then it increments the value of i by 1. That is, at that particular line the value of i remains same. It becomes effective from the next line onwards.

0 Comments:

Post a Comment

<< Home