Reputation: 3
My doubt is why in the following code the output is 2 and 1 respectively? Is this really OK? For my perception, the method 'm' should receive the value 1 since it's used the postfix operator on variable 'i' instead of the prefix operator.
public class PostfixDoubt {
public static void main(String[] args) {
int i = 1;
// why does m receive 2 as argument and not 1?
i = i++ + m(i);
System.out.println(i);
}
public static int m(int i) {
System.out.println(i);
return 0;
}
}
Bellow is the bytecode decompiled with javap:
public class PostfixDoubt {
public PostfixDoubt();
Code:
0: aload_0
1: invokespecial #8 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_1
1: istore_1
2: iload_1
3: iinc 1, 1
6: iload_1
7: invokestatic #16 // Method m:(I)I
10: iadd
11: istore_1
12: getstatic #20 // Field java/lang/System.out:Ljava/io/PrintStream;
15: iload_1
16: invokevirtual #26 // Method java/io/PrintStream.println:(I)V
19: return
public static int m(int);
Code:
0: getstatic #20 // Field java/lang/System.out:Ljava/io/PrintStream;
3: iload_0
4: invokevirtual #26 // Method java/io/PrintStream.println:(I)V
7: iconst_0
8: ireturn
}
Upvotes: 0
Views: 245
Reputation: 279990
This operation
i++
increments the value stored in the i
variable and returns its previous value. When i
is re-evaluated to be passed as an argument to
m(i)
the new, incremented, value is used.
int i = 1;
i = i++ + m(i);
looks like
1: 1 (i = 2) + m(i)
2: 1 (i = 2) + m(2)
3: 1 (i = 2) + Whatever value m(2) returns
4: whatever value is the result of that addition
5: that value is assigned to i
Upvotes: 3