Hitesh Kaushal
Hitesh Kaushal

Reputation: 181

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 !!!!!
    }
}

Upvotes: 17

Views: 830

Answers (2)

glee8e
glee8e

Reputation: 6419

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)

Upvotes: 23

Elliott Frisch
Elliott Frisch

Reputation: 201399

You have two operations operating on m.a in one call; in main

m.a += (m.function()?1:0);

pushes the value of a on the frame, and then invokes m.function() (which returns false), thus the ternary expands to m.a += 0; (and the value of m.a from the frame is added to 0 and stored in m.a). Thus the value is incremented in m.function() (and then reset in main). Consider it this way,

m.a = m.a + (m.function() ? 1 : 0);

The value of m.a is determined before the evaluation of m.function() (thus it is a post increment operation). For the result you expected, you could do

m.a = (m.function() ? 1 : 0) + m.a;

Upvotes: 19

Related Questions