Enter your E-mail Address below for Free E-mail Alerts right Into your Inbox: -

Tuesday

Why we should avoid "==" operator for comparing Integer objects in java

Why we should avoid "==" operator for comparing objects in java

The autoboxing is the technology introduced since java 5. Autoboxing in the sense converting  primitive types to its wrapper classes.
eg:- int to Integer. for more see  autoboxing and unboxing in java.

During comparison the Integer is converted into its primitive types. Even if the two have the same value it should return false because "==" also compares the reference, and it may be two objects in the java heap.

public static void main(String args[])
{
Integer i1 =260;
Integer i2 = 260;
if (i1 == i2) { System.out.println("i1 and i2 is equal"); }
else { System.out.println("i1 and i2 is not equal "); }


}

here it will print false because i1 and i2 are two objects in the heap and reference are different, so better to avoid "==" operator for comparing Integer Objects.

No comments:

Post a Comment