# Increment Test

Fes D Gaur
Ranch Hand
Posts: 54
public class IncrementTest{
public static void main(String args[])
{
int i=0;int j=0; int k=0; int l=0; int m=0;
i = i++ + i++;
System.out.println("i= " + i);
j = ++j + ++j;
System.out.println("j= " + j);
k = k++ + ++k;
System.out.println("k= " + k);
l = l++ + 0;
System.out.println("l= " + l);
m = m++;
System.out.println("m= " + m);
}//end main
}//end IncrementTest

Output:
i= 1
j= 3
k= 2
l= 0
m= 0

Could someone please explain the output?

Thanks,
Fes

Steve Morrow
Ranch Hand
Posts: 657
It might be easier if you explained what you found confusing about the output. Are you familiar with how pre- and post-increment operators work?

Steve Morrow
Ranch Hand
Posts: 657
I'll take the first one...

The right-hand expression is evaluated as follows, starting with the first i++, the second i++, then adding the results of those two expressions, then assigning *that* value to i...

Hope this helps. Again, if you state specifically what you're confused about, we can provide a detailed, specific answer, rather than simply repeating material that can easily be found in a tutorial.

Cheers!

Fes D Gaur
Ranch Hand
Posts: 54
The one I found confusing was k = k++ + ++k. But after reading about pre and post increment operators I'll try to answer this myself.

i = i++ + i++; //(post increment)i = 0 + (but now value of i=1) + 1, output = 1

j = ++j + ++j; //(pre increment) j = 1 + (pre increment) + 2, output = 3

k = k++ + ++k; //(post increment)k = 0 + (but now value of k =1) + 2,output = 2;

l = l++ + 0; //(post increment)l = 0 + 0, output = 0;

m = m++; //(post increment) m = 0;

Please feel free to add any comments to the above.

Thanks,
Fes

Barry Gaunt
Ranch Hand
Posts: 7729
A search of this forum may be helpful. This problem and similar ones have been discussed many times.

Steve Morrow
Ranch Hand
Posts: 657
Please feel free to add any comments to the above.

Looks like you got it.

Barry Gaunt
Ranch Hand
Posts: 7729
For instance The Classic