Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Integer Wrapper Class Related

Tags:

java

public class TestMe{
 public static void main(String[] args)  {
   Integer i = 128;
   Integer j = 128;

   Integer k = 12;
   Integer l = 12;

   System.out.println(i == j);  
   System.out.println(k == l);
  }
}

I'm getting the output: false true

Why is the 1st one false and 2nd one true?

like image 421
Kitts Avatar asked Dec 18 '22 18:12

Kitts


2 Answers

See: http://javapapers.com/java/java-integer-cache/

Short answer:

In Java 5, a new feature was introduced to save the memory and improve performance for Integer type objects handlings. Integer objects are cached internally and reused via the same referenced objects.

This is applicable for Integer values in range between –127 to +127.

This Integer caching works only on autoboxing. Integer objects will not be cached when they are built using the constructor.

like image 165
Itamar Avatar answered Dec 21 '22 11:12

Itamar


Integer values between -128 and 127 are cached for Integer.valueOf(...) methods which are often used by many operators, auto boxing and are called by compiler behind the scenes. You can increase this cached range by VM option -XX:AutoBoxCacheMax=size.

Your lines:

Integer k = 12;
Integer l = 12;

Are actually translated by compiler into:

Integer k = Integer.valueOf(12);
Integer l = Integer.valueOf(12);

That's why k and l instances have exactly one mutual Integer reference to the cached instance. This principle is also applicable to other wrapper classes.

like image 32
Cootri Avatar answered Dec 21 '22 09:12

Cootri