I am confused in the functioning of String.intern() function.
Expand|Select|Wrap|Line Numbers
- public class StringTest
- {
- public static void main(String[] args)
- {
- String test2 = new String("ABC");
- test2.intern();
- String test1 = "ABC";
- System.out.println("test1 == test2 is: " + (test1==test2));
- System.out.println("test1 == test2 is: " + (test1==test2));
- }
- }
test1 == test2 is: false
test1 == test2 is: false
Now the definition of String.intern() function says:
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
There is no String "ABC" in the pool when intern is called, so the same object is added to the pool; i.e. after call to intern, object referenced by test2 is in String pool. Now when test1 is created, then "ABC" exists in string pool so the same is returned from the pool and no new object is created.
So that means test1 and test2 references to the same object, so I am not able to understand why this strange result is comming.
Please guide me in this context.
Thanks in advance for any help.