When a string (constant expression) is just assigned to a String variable, JVM puts it in a special area called a pool. But when String object is constructed (using new), it is treated as other objects. The implication is when two String variables are assigned same value, there is only one string created in the pool. So, String s1 = "Hello"; String s2 = "Hello"; creates only one string in the pool, resulting (s1 == s2) to be true. The method intern() in String class does this. Hope this helps.
If two strings are created, s1 as the first statement: String s1 = "Hello" String s2 = new String("Hello") Then, will s1==s2 return true? What about s1.equals(s2)? What about s1.equals(new String("Hello")) What about s1.equals("Hello") Which of the above are valid and why?
s1 == s2 returns false. One object is in the string pool and one is on the heap. s1 and s2 reference two different objects. The rest return true because .equals() will do a character by character comparison of two different objects.
To what`s said by Paul Wheaton, it sound like == operator does more precise work than equals() method does. == checks the characters and whether two strings are in the same space of memory, whereas equals() method does only character comparing. To me that sounds strange. Maybe I`m wrong about the statement. Please someone let me know if I`m talking rubbish.
No you are wrong, but you are not talking rubbish, you are making an assumption that many people make so keep up with the posting. Here is an extract from my book aimed at the JDK 1.5 exam..
The String Pool
Another peculiarity of the way the String class works is that it uses a �pool� of strings to improve performance. If you create two String instances with the same sequences of characters, rather than occupy memory storing the same sequences multiple times, it stores them in a pool and each new String that requires access to that sequence of characters will point to them. This feature is tied in with immutability as a new String with the same sequence of characters as an existing String can be confident that the String it points to will not change over time.
The existence of the String pool can be very subtle, but it has come up on the programmers exam in the past. Strings are only put into the pool where they are created without the new operator.
Thus if you create two Strings with the same sequence of characters as
String s = �one�;
It will go into the pool, but if you create it with the new operator as
String s = new String(�one�);
It will not go into the pool.
The following code illustrates how Strings created without using the new Operator are actually the same object. Note you should never, ever test the equality of Strings using the == operator, this code is actually demonstrating that the strings are the same Object, i.e. It is testing the memory address.