Home > database >  How does Java handle precedence of operators when unary operators are involved?
How does Java handle precedence of operators when unary operators are involved?

Time:10-24

I have the following code in Java :

int a=5,b=10,c;
c =   b *   a - a   ;
System.out.println(c);

Now referring to the Java operators precedence table :-

Table

We will first evaluate the postfix a and then prefix a and b, which gives us :

c= 11 * 7 - 5 = 72

But this answer is wrong, and the correct answer is 60 What am I doing here?

CodePudding user response:

According to the Java Language Specification section 15.7.1,

The left-hand operand of a binary operator appears to be fully evaluated before any part of the right-hand operand is evaluated.

This applies, in your expression, to the - operator. That means that b * a is fully evaluated before any part of a is evaluated.

When b * a is evaluated, a side-effect is that a is increased to 6. The value of b * a is 66, because with a prefix operator, the "post-operation" value of the variable is used in the calculation, so this is 11 * 6.

Once b * a has been evaluated, the right hand operand of the - operation can be evaluated. This is a , which evaluates to 6, but increases a to 7.

The subtraction is therefore 66 - 6, which is 60.

Unfortunately, you have been misled by the table in the Oracle Java tutorial, which suggests that postfix operators are always evaluated before prefix operators. Since this statement contradicts the Java Language Specification, I can only imagine that the authors of the Oracle Java tutorial actually intended something different, but didn't express themselves very well.

CodePudding user response:

The difference between a and a is that in first it will increase the value of a and then use it's result as the input for next expression but a will use the value of a for the expression and then increase a.

Also precedence of multiplication is higher than addition/substraction. In your case:

c =   b *   a - a   ;
c = ((  10) * (  5)) - (a  )
c = (11 * 6) - (6  ) // a's value is 6 because of increment.
c = 66 - 6 // A value will become 7 but 6 will be used.
c = 60
  • Related