Search code examples
javavariable-assignmentincrementternary

Increment in function overwritten by +=


A method called in a ternary operator increments a variable and returns a boolean value. When the function returns false the value is reverted. I expected the variable to be 1 but am getting 0 instead. Why?

public class Main {
    public int a=0;//variable whose value is to be increased in function
    boolean function(){
        a++;
        return false;
    }
    public static void main(String argv[]){
        Main m=new Main();
        m.a+=(m.function()?1:0);
        System.out.println(m.a);//expected output to be 1 but got a 0 !!!!!
    }
}

Solution

  • Basically m.a += (m.function() ? 1 : 0) compiles into

     int t = m.a; // t=0 (bytecode GETFIELD)
     int r = m.function() ? 1  : 0; // r = 0 (INVOKEVIRTURAL and, IIRC, do a conditional jump)
     int f = t + r; // f = 0 (IADD)
     m.a = f // whatever m.a was before, now it is 0 (PUTFIELD)
    

    The above behavior is all specified in JLS 15.26.2 (JAVA SE 8 edition)