I'm wondering why the following code snippet compiles in Java 7 without a warning
Map<String, Object> map = new HashMap<>();
map.put("key", 0);
if (map.get("key") != 0) {
System.out.println("what?!");
}
Studying the generated bytecode reveals that the compiler boxes the 0
used in the if
statement to an instance of Integer
(using Integer.valueOf(0)
) and then compares it with the result of the get
using reference equality. Surprisingly enough the code doesn't print anything because instances of small integers are reused. But if one replaces 0
with say, 4096
in both cases, the program prints "what?!"
But my question is not why this code works or doesn't - it's an offense to write such a code. I'd rather expect the compiler to reject it completely! Why doesn't it?