Wednesday, May 25, 2011

Integer.valueOf(1) != 1

Assume you have the following snippet:
public class Bar {

static {
// ...
}

public static final Integer DEFINITELY_ONE = 1;

public static void main(String[] args) {
int zero = DEFINITELY_ONE;
System.out.println(one == 1);
}

}

Should be true, right? Not exactly, depends on what you have in the static block. Try to place this code for example:
try {
Field field = Integer.class.getDeclaredField("value");
field.setAccessible(true);
field.setInt(Integer.valueOf(1), 0);
} catch (Exception t) {
//...
}

Now because of autoboxing and integer cache we get false as Integer.valueOf(1) now returns zero.