rgh rgh - 3 months ago 9
Java Question

++(new Integer(100)); //error

Could anyone tell me why I get a compiler error here?

class NewInteger{
public static void main(String[] args){
Integer i = new Integer(200);
Integer j = ++i; //ok
Integer k = ++(new Integer(300)); //compile error: unexpected type
// required: variable
// found: value
}
}


Seems to me the offending line is just a terser version of the two preceeding it.

Answer

++ reads from a variable, increments the value read, and writes back to the variable. new Integer(300) is not a variable, you can't write to it.

That's the critical difference between your two examples: In the j = ++i case, ++ has something it can write back to (i). In the second case, it doesn't.


(Using "variable" here the way the JLS frequently [though oddly not always] does, to mean both local variable and instance or class field.)