Jay Laughlin
Jay Laughlin

Reputation: 154

Java postfix operator precedence

In the code sample below I am struggling with the idea that the postfix operator is somehow happening before the comparison. I know the postfix has a higher precedence but according to java docs:

the postfix version (result++) evaluates to the original value.

So in this code:

    int number = 2;
    boolean bob = number < number-- * number;
    System.out.println(bob +" "+number );

number should be and is 1 when it outputs. That's expected. The issue is that bob is false. If the number still uses the "original value" despite the postfix -- then shouldn't the problem evaluate to: bob = 2 < 2 * 2, Last I check 2 was less than 4? Is the other number that is being multiplied at the end somehow changed to 1 then (that doesn't make sense to me)?

I know the problem isn't with the comparison operator in there because this works properly:

    number = 2;
    boolean test = 2 < number++;
    System.out.println(test);

2 < 2 correctly here, then it increases number. Why is it different in the previous example?

Upvotes: 0

Views: 70

Answers (1)

Ayrton
Ayrton

Reputation: 2303

number-- evaluates to 2, but all references to number after that evaluate to 1. Therefore number-- * number evaluates to 2 * 1, which is 2.

Upvotes: 3

Related Questions