1

Can someone tell me why this code results in 1?

What I think should happen is myInt gets modded by 10, resulting in 1, then myInt gets incremented and should become 2. However, it seems the incrementation is discarded.

int myInt = 21;

myInt = myInt++ % 10;

System.out.println( "myInt: " + myInt );
Felix Kling
  • 756,363
  • 169
  • 1,062
  • 1,111
OKGimmeMoney
  • 575
  • 2
  • 6
  • 19
  • 1
    I'm not sure what sort of answer you're looking for. Your intuition was wrong, and actually the increment happens first, then the assignment. You just verified this. – Ismail Badawi Dec 02 '13 at 05:32

3 Answers3

2

Google for difference between postincrement and preincrement.

This will work for your case

int myInt = 21;

myInt = ++myInt % 10;

System.out.println( "myInt: " + myInt );
0

Rather than theoretically, I think it would be good to explain through example.

there are two type of increment

a++ (post increment)

++a (pre increment)

If a = 10;

i=++a + ++a + a++; =>
i=11 + 12 + 12; (i=35)

i=a++ + ++a + ++a; =>
i=10 + 11 + 12; (i=33)
vinay kumar
  • 1,421
  • 13
  • 33
0

I believe the operator "variable++" is a post-increment operator. As a result the original value is returned BEFORE incrementing.

So in your case:

  1. myInt++ returns 21
  2. myInt++ is process, myInt now equals 22
  3. 21 % 10 is processed and assigned to myInt, myInt equals 1
Henri Lapierre
  • 1,992
  • 4
  • 17
  • 19