Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this Java operator precedence being ignored here?

The following code prints out "3", not "4" as you might expect.

public class Foo2 {
    public static void main(String[] args) {
        int a=1, b=2;             
        a = b + a++;
        System.out.println(a);
    } 
}

I understand how. The postfix increment happens after the value of "a" has been loaded. (See below).

What I don't quite understand is the why. The operator precedence of postfix ++ is higher than + so shouldn't it execute first?

% javap -c Foo2

Compiled from "Foo2.java"
public class Foo2 extends java.lang.Object{
public Foo2();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   iconst_1
   1:   istore_1
   2:   iconst_2
   3:   istore_2
   4:   iload_2
   5:   iload_1
   6:   iinc    1, 1
   9:   iadd
   10:  istore_1
   11:  getstatic       #2; //Field java/lang/System.out:Ljava/io/PrintStream;
   14:  iload_1
   15:  invokevirtual   #3; //Method java/io/PrintStream.println:(I)V
   18:  return
like image 408
Aaron Fi Avatar asked Sep 28 '09 21:09

Aaron Fi


People also ask

What is operator and operator precedence in Java?

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator −

Which operator is considered highest precedence?

Answer: Postfix operators i.e () [] . is at the highest precedence.


1 Answers

Postfix ++ increments the value of variable, and returns the value that was there before the increment. Thus, the return value of operator++ in your example will be 1, and of course 1 + 2 will give 3, which is then assigned to a. By the time of assignment, ++ has already incremented the value of a to 2 (because of precedence), so = overwrites that incremented value.

like image 67
Pavel Minaev Avatar answered Nov 02 '22 08:11

Pavel Minaev