Saturday, May 8, 2010

equals method in JAVA

equals method of Object class and String class

Consider the below code


myClass obj1=new myClass();
myClass obj2=new myClass();


String str1=new String("AAAA");
String str2=new String("AAAA");

System.out.println(obj1.equals(obj2));
System.out.println(str1.equals(str2));

OUTPUT:
false
true

In both the cases two objects were created but for Strings the result is true and for myClass object the result is false.
The reason for this is
In object class the equals method compares the references and returns true if the references are point to the same object.
But in String class the equals method is overridden to check the values of the string object so it returns true.

2 comments:

  1. In case of string, it will return true because when we create the string object for the first time, it'll be created and stored in string pool. Again if the string object is created on the same value then it'll refer to the same value in that pool.

    ReplyDelete
  2. HI sumit,

    the string pool is used when we create string using the command below i believe
    String a="abc"
    But when we create using new String("abc") new object is created in the heap memory. Please check the intern method of string class. if only intern is used then it will point to the same string constant in the pool.
    will wait for your reply.

    ReplyDelete

About Me