Java Quiz of the Day II

Patrick Jayet
XRB’s Blog
Published in
1 min readMay 19, 2010

What gives:

Integer a = 100, b = 100;
Integer c = 200, d = 200;
System.out.println( (a == b) == (c == d) ); // A

Response: counter intuitively, the program prints ‘false’ out. Integer in Java is a non-native class, where ‘==’ means ‘reference equality’ (two variables are reference equal if they are pointing to the same object). From there we would expect the expression of line (A) to be reduced to ‘false == false’, but it is slightly more complicated: the Integer class has the particularity that all Integer (like Short) in the range [-128, 127] are shared. This means the two variables ‘a’ and ‘b’ are actually pointing to the same shared object. Hence the expression of line (A) is in fact reduced to ‘true == false’.

--

--

Patrick Jayet
XRB’s Blog

Polyglot (FR, DE, EN, ES), polyglot programmer (Java, Groovy, Ruby, Swift, Objective-C, Scala, Python, O’Caml) polyglot methodologist (Scrum, Kanban, Lean).