Comparison of two short objects giving unexpected results

I was executing the following codes, got some unexpected results

class Test { public static void main(String[] args) { Short i = 122, j = 122; if (i == j) { System.out.println("true"); } else { System.out.println("false"); } } } 

and

  class Test { public static void main(String[] args) { Short i = 1222, j = 1222; if (i == j) { System.out.println("true"); } else { System.out.println("false"); } } } 

When I executed this code, the first code gives true output, and the second code gives false output. I know when we compare objects using == , it does not look for actual values, but simply compares the links. But in the first case, he compares the values, and in the second - no.

+7
java
source share
1 answer

Short has an internal cache for values ​​from -128 to 127. Thus, for numbers in this range, the same Short instance is returned. When you compare using ==, Java is compared by instance and therefore returns true . When numbers are outside this range, two different instances are created. That way they will fail when comparing == , returning false .

Thanks to this caching, we save some memory and have faster code.

See the following method from the JDK 1.7 source code. It was there with 1.5

 public static Short valueOf(short s) { final int offset = 128; int sAsInt = s; if (sAsInt >= -128 && sAsInt <= 127) { // must cache return ShortCache.cache[sAsInt + offset]; } return new Short(s); } 

This caching also exists for other wrapper classes; you can check out the Java documentation for more details.

+10
source share

All Articles