25
kfish
8y

Less rant, more mildly interesting Java trivia.

Integer i0 = 3; Integer i1 = 3;
Integer i2 = 300; Integer i3 = 300;

i0 == i1 is true as expected
i2 == i3 is actually false

Java caches -128 to 127 Integer objects for faster perf so when you're inside that range, the objects are indeed the same, but because == checks object equality, the Integer outside of the range is not cached and had to be initialized, so i2 and i3 are two different objects.

You can totally break some tests this way :)

Comments
  • 9
    Object == Object in general is not a good idea
  • 0
    @maximizer oh not at all, but it's still used way too often with objects. But its interesting that you'd expect certain behaviors from primitives, but their delegate object has its own perks.
  • 2
    Objects.equals(saves,day);
  • 1
    One of the first things I learned in school in Java class: use the equals method instead of == operator. For reasons like these I do add value to a solid educational background in software engineering.
  • 0
    Most definitely, however , with this knowledge of the cache, one can actually modify cached integer values, albeit within its own context. But if I can inject code to a Java module, I can make it think 3 is actually 20. It's neat.
  • 0
    @kfish You killed my lust to learn Java 🤢
  • 0
    @Gauthier Java is wonderful, this little tidbit is another piece of the puzzle! Now you're a step closer to becoming a Java master! :)
  • 3
    i2.intValue() == i3.intValue()
  • 0
    i2.equals(i3);
Add Comment