People, you are forgetting that the process of placing literal strings in the pool is called "interning". The class String has a method called intern(). This method puts any string into the pool, even if it is not in the pool initially (not literal). This means that code like this:
String a = "hello";
String b = new String("hello");
b = b.intern();
System.out.println(a == b);
will print "true
".
Now, why would someone need this? As you can imagine, string comparison a.equals(b)
might take a long time if strings are the same length but different close to the end.
(Just look at the .equals() source code.).
However, comparing references directly is the same as comparing integers (pointers in C speak), which is near instant.
So, what does this give you? Speed. If you have to compare the same strings many, many times, your program performance will benefit tremendously if you intern these strings. If however you are going to compare strings only once, there will be no performance gain as the interning process itself uses equals().
I hope this explains this.
thanks