Tuesday, 25 February 2014

The .equals() and == confusion

==(comparison operator)

Every thing is a class or an object in java .Thus == is used normally to compare two values of primitive type such as int,float etc. ,But in the case of String or Wrapper classes it checks that whether two objects have same memory address or not.

Blown by it! But stay with me as this article will clear your basics about object comparison.

What == does is that it checks memory addresses in case of objects.

Let's judge it with an example.

Integer i1 = 1000;

Integer i2 = 1000;

if(i1 != i2) System.out.println("different objects");

Produces the output:

different objects


As i1 and i2 are different objects thus the output is desired.

Wait this get's more weird!

Integer i3 = 10;

Integer i4 = i3;

if(i3 == i4) System.out.println("same object");


This example produces the output:

same object


Yikes!What happened with == and != ? Why is != telling us that i1 and i2 are different objects, when == is saying that i3 and i4 are the same object? In order to save memory, whenever in java if we assign one object to another ,the object is not copied but both objects share same memory reference.

Note: When == is used to compare a primitive to a wrapper, the wrapper will be

unwrapped and the comparison will be primitive to primitive.


Such as

Integer a=10;

int b=10;

System.out.println(a==b); //a is first unboxed to its primitive value and then comparison took place


Output is

true

.equals() It checks whether the two objects are meaningfully same i.e if two wrappers are taken into consideration they are equal if they are of same type and have same primitive value.

Example

Integer i1 = 1000;

Integer i2 = 1000;

if(i1.equals( i2)) System.out.println("meaningfully same");


Output will be

meaningfully same

Why we use .equals() for string comparison?

As you know String is a class if use == that will compare memory addresses of String objects.

Consider the following example:

public class t{

public static void main(String[] args)

{

String x="Tilak";

String y="Tilak";

if(x==y)System.out.print("same");

}

}


Output: same


You must be wondering as,I said that == compares memory addresses but in this String example it works fine.But try to understand the mechanism behind it.

The topic which we need to understand to clear this concept is String Pool.


String Pool

To save memory java has so called String Pool which contains all the declared Strings .When two or more String objects have same value they refer or point to the same String value stored in pool.



So the above example worked not because “Tilak”==”Tilak” but it worked because a single copy of “Tilak” is present in the pool and both x and y point to this single copy.


Thus using .equals() ensures that values are compared not their memory addresses.


To know more about .equals(),Please read about .hashCode().


No comments:

Post a Comment