Java: why == works for 127 but not for 1000;
Nikos Papadakis@nikos_pap
Hello, I am CS student in Thessaloniki, learning Java for my exam. I found something strange and my professor only said "look it up" xD
Integer a = 127;
Integer b = 127;
System.out.println(a == b); // true
Integer c = 1000;
Integer d = 1000;
System.out.println(c == d); // false ;;
Why the same code gives different result; Is it a bug in my JDK (Temurin 21); Should I always use equals for Integer; Thank you!
Top answer
This is classic. Integer a = 127 is autoboxing, compiler writes Integer.valueOf(127). valueOf has a cache for -128 to 127, required by the Java spec, so a and b are the same object and == says true. 1000 is outside the cache, you get two different objects, == compares references, false.
Rule: never == on Integer, Long and friends. Use equals, or Objects.equals if it can be null, or compare as int. Not a bug in Temurin. Your professor is right to make you look it up, this question is in half of Java interviews in Poland.
Get the best of #compiling weekly
One email each Monday with the most useful posts. No spam; unsubscribe in one click.
Comments
Sign in to join the conversation.
Sign in to commentTomasz Kowalski@tomasz_k
This is classic. Integer a = 127 is autoboxing, compiler writes Integer.valueOf(127). valueOf has a cache for -128 to 127, required by the Java spec, so a and b are the same object and == says true. 1000 is outside the cache, you get two different objects, == compares references, false.
Rule: never == on Integer, Long and friends. Use equals, or Objects.equals if it can be null, or compare as int. Not a bug in Temurin. Your professor is right to make you look it up, this question is in half of Java interviews in Poland.
Nikos Papadakis@nikos_pap
Thank you! So the cache is the reason. And if I start the JVM with bigger cache it would be true for 1000 also;
Tomasz Kowalski@tomasz_k
Yes, -XX:AutoBoxCacheMax=2000 makes it true. Do not do it. Code that depends on it is broken code that works by accident.
Omkar Joshi@omkar_java
Can confirm interview question. Also nasty in real life: two Long IDs from Hibernate compared with == in a service. Worked in testing because IDs were small, failed in production once the IDs went past 127. True story from a bank project.
Andrei Mureșan@andrei_cluj
Nikos, after the exam come work in Cluj instead of Germany, we have Java and better coffee ;)
Peter Hughes@amiga_pete
In 1987 we had sixteen bits and no objects, so this exact problem could not happen to us. Plenty of others could. Lovely question, Nikos. Cheers, Pete
Nikos Papadakis@nikos_pap
Pete what problems did you have with sixteen bits; I want to hear the story!