Comparison of autoboxed integer object in Java


When we assigned an int to Integer object, it is first converted to an Integer Object and then assigned. This process is termed as autoboxing. But there are certain things which you should consider while comparison of such objects using == operator. See the below example first.

Example

Live Demo

public class Tester {
   public static void main(String[] args) {

      Integer i1 = new Integer(100);
      Integer i2 = 100;        
      //Scenario 1:
      System.out.println("Scenario 1: " + (i1 == i2));

      Integer i3 = 100;
      Integer i4 = 100;        
      //Scenario 2:
      System.out.println("Scenario 2: " + (i3 == i4));

      Integer i5 = 200;
      Integer i6 = 200;        
      //Scenario 3:
      System.out.println("Scenario 3: " + (i5 == i6));

      Integer i7 = new Integer(100);
      Integer i8 = new Integer(100);
      //Scenario 4:
      System.out.println("Scenario 4: " + (i7 == i8));
   }
}

Output

Scenario 1: false
Scenario 2: true
Scenario 3: false
Scenario 4: false
  • Scenario 1 - Two Integer objects are created. The second one is because of autoboxing. == operator returns false.

  • Scenario 2 - Only one object is created after autoboxing and cached as Java caches objects if the value is from -127 to 127. == operator returns true.

  • Scenario 3 - Two Integer objects are created because of autoboxing and no caching happened. == operator returns false.

  • Scenario 4 - Two Integer objects are created. == operator returns false.

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 18-Jun-2020

188 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements