Comparison of Autoboxed Integer Objects in Java

Hi! in this tutorial we are going to understand the comparison of Autoboxed Integer objects in Java.

First, let me tell you what is autoboxing exactly.

Autoboxing is an automatic conversion of primitive types to the object of their corresponding wrapper classes. For example, converting int primitive type to an object of the corresponding Integer wrapper class, double to Double, etc. So, let’s see a simple code converting an int variable to Integer-

class auto
{
  public static void main(String ar[])
  {
    int x=50;
    Integer y=x;//autoboxing
    System.out.println(x);
    System.out.println(y);
   }
}

Output-

50
50

Here, we have declared a primitive int variable which is set to 50. Now, it is converted into an object of Integer wrapper class and stored in y.

Java program for comparison of autoboxed integer objects

When we assigned an int variable to an Integer object, it is first converted into an object then assigned to the Integer object. Now, we will discuss some interesting comparisons of Autoboxed Integer Objects with the help of a program. So, let’s see the code now-

class auto
{
  public static void main(String ar[])
  { 
    //CASE-1
    Integer x=500;
    Integer y=new Integer(500);
    System.out.println(x==y);
    //---CASE-1 ENDS---//
   
    //CASE-2
    Integer x1=new Integer(200);
    Integer y1=new Integer(200);
    System.out.println(x1==y1);
    //---CASE-2 ENDS---//

    //CASE-3
    Integer x2=10;
    Integer y2=10;
    System.out.println(x2==y2);
    //---CASE-3 ENDS---//

    //CASE-4
    Integer x3=400;
    Integer y3=400;
    System.out.println(x3==y3);
    //--CASE-4 ENDS---//
   }
}

Output-

false
false
true
false

Let’s discuss all the cases taken in the code above one by one.

CASE-1

In this case, two Integer objects will be created. object has been created using autoboxing whereas y object is created using new operator. That’s why when compared using == operator will return false.

CASE-2

In this case, both the objects x1 and y1 are created using the new operator. So, they both point to different locations. Hence, when compared using == operator will return false.

CASE-3

In this case, only one object is created which is pointed by x2 and y2. And in Java the values from -128to 127 are cached. So, the same objects are returned. So, when compared using == operator will return true.

CASE-4

In this case, here two different objects are created as the values exceed the range of -128 to 127. No caching takes place. Hence, when compared using == operator will return false.

I hope, this tutorial helps you.

 

Leave a Reply

Your email address will not be published. Required fields are marked *