Tiger Schueler’s Post

When I was practicing Java algorithms yesterday, I ran into the good ol’ .equals() method, one of the more well-known methods. I knew I needed to use it when comparing instances of wrapper classes like Integer and Character, but I wanted to understand why. While digging, I came across something really interesting about Integer. If an Integer value is in the range -128 to 127 (that’s -(2^(8-1)) to 2^(8-1)-1), Java actually caches the value. Thanks to this caching, the == operator can sometimes work instead of .equals(). Another really cool thing Java does is autobox and unbox values automatically. For example: Integer x = 5; // autoboxed into the wrapper class Integer y = Integer.valueOf(5); // manual equivalent int z = x;   // unboxed back into primitive int This lets you move seamlessly between primitives and wrapper objects, which is especially handy when working with collections. You definitely wouldn’t want to rely on the caching in production code, but the JVM does it as a small efficiency boost because these numbers are so commonly used. Makes me wonder what else the JVM is quietly doing under the hood.

  • No alternative text description for this image

Nice illustration, best core!

To view or add a comment, sign in

Explore content categories