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
  • 795,719
  • 175
  • 1,089
  • 1,143
OKGimmeMoney
  • 575
  • 2
  • 7
  • 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,451
  • 13
  • 33
  • 1
    At least in C, `++a + ++a + a++` would be undefined behavior. How is this in Java? – Felix Kling Dec 02 '13 at 05:36
  • @FelixKling It's not undefined in Java. (http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.7) – Ismail Badawi Dec 02 '13 at 05:40
  • @FelixKling - it works in java. – vinay kumar Dec 02 '13 at 05:41
  • @Ismail: This doesn't give a definite answer about those operators though (at least I don't see it). But after browsing some questions on SO, it seems the behavior is indeed defined. – Felix Kling Dec 02 '13 at 05:47
  • @vinaykumar: It "works" in C as well, but the actual result can differ from machine to machine. – Felix Kling Dec 02 '13 at 05:48
  • @FelixKling - I don't have indepth knowledge on C, but very curious to know how it differs from machine to machine, whether it will throw an exception or, will give a wrong result? – vinay kumar Dec 02 '13 at 05:58
  • Have a look at: https://en.wikipedia.org/wiki/Undefined_behavior. It doesn't throw an exception, you would just get different results. – Felix Kling Dec 02 '13 at 06:04
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
HLP
  • 2,142
  • 5
  • 19
  • 20