Given the following code, will ixAdd do what you\'d expect, i. e. return the value of ix before the increment, but increment the class member before leaving the function?
Well, let's look at the bytecode (use javap -c
to see it yourself):
Compiled from "PostIncTest.java"
class myCounter extends java.lang.Object{
myCounter();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."":()V
4: aload_0
5: iconst_1
6: putfield #2; //Field _ix:I
9: return
public int ixAdd();
Code:
0: aload_0
1: dup
2: getfield #2; //Field _ix:I
5: dup_x1
6: iconst_1
7: iadd
8: putfield #2; //Field _ix:I
11: ireturn
}
As you can see, instructions 6 and 7 in ixAdd()
handle the increment before the return. Therefore, as we would expect, the decrement operator does indeed have an effect when used in a return statement. Notice, however, that there is a dup
instruction before these two appear; the incremented value is (of course) not reflected in the return value.