This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
If this line is executed, 1) it first creates new String("java") on the heap.
2) Then it will call new String("java").intern().
3) Calling intern() means saying jvm to search String constant pool and find reference of String referenced by current calling object and return that reference, means find reference of "java" in String constant pool and return that reference to s3. Now s3 will refer to a String literal "java".
4)String s4 ="java"; and s4 also takes reference of "java" from string constant pool.
5) so both s3 and s4 are referring to same object that is referred string constant pool reference, so s3==s4 becomes true. [ December 30, 2008: Message edited by: punit singh ]
The intern method converts duplicated Strings to shared ones.When called on any string object it makes all other String objects with the same value(checked through the equals method) point to the same object in the String pool. This method return of the value of the String Also for any two strings a and b a.intern() == b.intern() is true if and only if a.equals(b) is true.
Like we have String a = "ja" String b = "va" String c = "ja"+b; String d = "java"; c.intern();
Now calling c==d should return true
But i tried Abhi's example It wasnt giving expected results
The output of the above prg is : 1. java 2. java false
Can someone explain this unusual behaviour ?or there is some problem in my understanding of the intern method