This week's book giveaway is in the Mac OS forum. We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line! See this thread for details.
As a java programmer I learnt that, to compare String equality we cannot use "==". only .equals() method will compare the string contents.
Then I learnt from Kathy Sierra(SCJP Guide) that when a new String variable is declared assigning it a literal value then JVM will look for similar String objects available in the pool and if it is available, then it will assign the same object to the newly created string reference. So by this process two strings having same values will have same object reference, and hence "==" will work correctly.
I want to know in which case .equals() will be useful for Strings so that "==" test will fail even for same string values.
Is it like only for String objects created using "new String()" keyword we need to use .equals() to compare and for all other String objects "==" will compare correctly?
inside main method i tried executing the following:
produced the output as "true".
Kindly help me to understand this basic String comparison.
When you create String objects without using a new operator it is stored in the string pool
Ex : String s1 = "abc";
Now if you write String s2 = "abc" ; then this time new object will not be created. The String value will be first searched in the String pool and as "abc" is already present new object is not created and so s1 and s2 will be pointing to "abc". If the object "abc" is stored at address 100 then the references s1 and s2 both will have value 100.
When we create String objects using new operator , they are not stored in the string pool so even if the values of both the String objects is same , the references are not pointing at the same object
String s1 = new String("abc"); stored at location 100
String s2 = new String("abc"); stored at location 200
Here s1==s2 is false but s1.equals(s2) will be true..
Mohamed Iqzas wrote:Is it like only for String objects created using "new String()" keyword we need to use .equals() to compare and for all other String objects "==" will compare correctly?
Its not like that. As a general convention, you should always use 'equals' method instead of '==' operator. The operator '==' ensures that if both references are referring to exactly same objects (not two different objects whose contents are similar).
Now, when you compare two Strings, all you are interested is that if contents of both Strings are same or not. So, I don't see any solid reason to use '==' operator (which can result false even if contents of the Strings are same).
By the way, you have to be very very sure and very very careful when you use '==' operator. The best thing is never to use that operator along with objects of immutable class (unless you really really really have to).