Please observe the following code: String a = new String("java"); String b = new String("java"); System.out.println(a == b) // this prints false System.out.println(a.equals(b)); // prints true String c = "java"; String d = "java"; System.out.println(c == d) // this prints true System.out.println(c.equals(d)); // prints true Can you please explain me the reason for this? thanks! Murthy
Hi Murthy String a = new String("java") creates a String object. System.out.println(a == b) is false as it does shallow comparison. It compares Objects instead of the content of the object. The method equals() does deep comparison. It compares the content of the String. Thus, System.out.println(a.equals(b)) prints true. As for String c = "java"; String d = "java"; since there's no "new" used, it does not create a new object instead is pointing to the same string in the string pool. Since it's the same string, == will return true. I hope this brief explanation helps a bit. you should do a search here. This topic has been discussed a lot here. I'm sure the explanations provided by the other ranchers are much better.
--------------------<p>Karen Leoh<br />Sun Certified Programmer for Java™ 2 Platform
posted 16 years ago
Karen, thanks for your nice explanation. Hence, Can I say that, whenever we use "new" to create the same string ( like "java" in this example), == always returns FALSE as it compares the objects. please correct me , if I am wrong and give some example. [ June 04, 2002: Message edited by: Murthy Kompella ]