Friday, September 11, 2009

Some thought on "=="

In terms of java objects, "==" comparison means two references pointing to the same object instance. Now consider Immutable classes (immutable :? Well immutable class is a class whose objects can't be modified once created or state can't be changed, they don't expose any setter methods). String and all wrapper classes are immutable in java (wrapper:? Well wrapper classes are Integer for int, Float for float, Double for double etc ).

Some code snippet :-

String i = "test"; String i1 = "test"; String j = new ("test"); String j1 = new ("test");

Now compare:-

1) i==i1 2) j==j1 3) i==j.

1- is true, 2 and 3 are false. As String is a class in java, so when we create a String it will create a String variable which points to "test". So i and i1 should be 2 different references and would have returned false. Here's the reason when we create i="test", this gets created on method area and when we initalize another i1="test", before creating a new memory allocation on method area content checking is done to identify wether "test" String exist. If a match is found i1 points to the same "test" to which i was pointing too, resulting i==i1, true.

When we create the same String j = new String("test"). This creates a new object and memory allocation happens on heap. So if we compare j==j1, which are two different memory location results in false.

Considering the same scenario for wrapper classes, I am taking int and Integer

int i=1; int i1=1; Integer j = new Integer(1); Integer j1= new Integer(1);

Now Compare :-

1) i==i1 2) j==j1 3) i==j

Here 1,3 are true and 2 is false. Reason for having 2 is false because we have created two new Objects and comparing thier references which points to two different memory locations.

Now int is a prmitive type and is not a classs. For comparing two primitives is same as comparing two values, but comparing primitives and wrapper class type it return true and that's the catch for autoboxing and unboxing. Converting int to an Integer is called autoboxing and Integer to an int is called unboxing. This is implemented in Integer class something called as IntegerCache to support the object identity semantics of autoboxing for values.

2 comments:

  1. How can i find out more java concept in this site?

    Thanks in advance,

    Guru

    and send me on
    murugadoit@gmail.com

    ReplyDelete