Thursday, September 16, 2010

The difference between .equal and ==

The '.equal' method does deep comparison of the objects. 'equal' method compares what an object points to rather than pointer itself. The operation of the equal method and '==' operator has some strange effects when use to compare Strings.

String s = "Hello";
String s2 = "Hello";
if (s==s2){
System.out.println("Equal");
}

The creation of two strings without the use of the new keyword will create pointers to the same String in the Java String pool.

String t = new String("Hello");
string u = new String("Hello");
if (t==u){
System.out.println("Equal with new operator");
}

So now t and u are two separate strings. == operator only compares the address of the object not
the value.Now t and u have different addresses.

No comments:

Post a Comment