Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 !!!!!
    }
}
like image 548
Hitesh Kaushal Avatar asked May 21 '16 04:05

Hitesh Kaushal


1 Answers

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)

like image 152
glee8e Avatar answered Sep 20 '22 08:09

glee8e