0

I have a question,
In Java, does Math.min bind tighter than ++?
Let me illustrate with an example and maybe someone can explain to me why I get the results I get.

Here's a method I run:

private static void testIncrement() {
    int x=10;
    System.out.println(x++);
    System.out.println(x);

    x=10;
    System.out.println("-----------");
    System.out.println(++x);
    System.out.println(x);

    x=10;
    System.out.println("-----------\n"+x); //10
    x=Math.min(255, x++); 
    System.out.println(x); **//x=10 WHY NOT x=11?**

    x=10;
    System.out.println("-----------\n"+x);
    x=Math.min(255, ++x);
    System.out.println(x);
}

The results are:

10
11
-----------
11
11
-----------
10
10
-----------
10
11

On the line where I put //x=10 WHY NOT x=11?
I wonder why x is 10 and not 11. Maybe someone can explain this to me.

It looks as if Math.min create a copy of x (which is 10 at this time) which it uses to do Math.min. Then the original x is incremented from 10 to 11, but the copy which is still 10 comes out of Math.min and overwrites the incremented one.

Does this make sense? Does anyone have an explanation for why x is 10 and not 11 in this case?

Thanks

PS - I totally understand How do the post increment (i++) and pre increment (++i) operators work in Java?

Community
  • 1
  • 1
Adrian
  • 5,603
  • 8
  • 53
  • 85

1 Answers1

4

Let's deconstruct this line:

x = Math.min(255, x++); 

The x++ means "remember the original value of x; then increment x; then the value of the expression is the original value". All of this happens before the assignment. So it's equivalent to:

int tmp = x;               // x = 10, tmp = 10
x = x + 1;                 // x = 11, tmp = 10
x = Math.min(255, tmp);    // x = 10

Hopefully that should make it clear. In particular, this has nothing to do with Math.min itself - it's just behaving as a normal method invocation. See section 15.14.2 of the JLS for more details.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I agree, but then why is my program outputting 10 both times, instead of 11. After all, it is doing a post increment. Any idea? – Adrian Nov 22 '12 at 22:06
  • @Adrian: The increment is after the evaluation of the expression, but *before* the assignment of the value returned from the method call... so the value of `x` ends up as 10 (which is what `Math.min` returns). Read the "expansion" - I'll add some comments. – Jon Skeet Nov 22 '12 at 22:07
  • oh I see it, I missed the temp in x = Math.min(255, tmp). Thanks! :) – Adrian Nov 22 '12 at 22:08