Here a little explanation:
"a"
create the String "a" in the intern pool if not already present
new String("a")
because the parameter is "a", the string "a" is created in the intern pool (if not already present) and a copy of "a" is created out of intern pool
- taken any string s
s.intern()
returns an intern copy of that string if present in the intern pool. If not add that string to the intern pool and returns the new copy.
A reference for intern() method:
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.
Note: to create a String
and don't add it to the intern pool you can use an array of chars as parameter of String constructor:
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
Here is the reference to the jls where it is explained that a string literal is present in the intern pool of strings:
A string literal is a reference to an instance of class String (§4.3.1, §4.3.3).
Moreover, a string literal always refers to the same instance of class
String. This is because string literals - or, more generally, strings
that are the values of constant expressions (§15.28) - are "interned"
so as to share unique instances, using the method String.intern.
Here a step by step explanation to the last comment:
// Creates the string "123", add it to the intern pool and assign "123" to s
String s = "123";
// s.intern() returns the intern string of s. Because s is already the
// string "123" present in the intern pool s and s.intern() are the same
System.out.println(s == s.intern());// true
// "123" is already in intern pool. new String("123") create a new String
// that equals "123" but it is a different object
String s2 = new String("123");
// It prints false because s2 is equals to "123", but not the same object
// because a new String was created in the preciding row
System.out.println(s2 == s);// false
// It prints true because s2.intern() returns the string present in the
// intern pool that is equals to s2. That string exists and is "123"
System.out.println(s2.intern() == s); // true
Additional note: For every string s that equals s2, s.intern() == s2.intern() also if s == s2 returns false.
// If s equals s2 but are not the same
if (s.equals(s2) && s != s2) {
// THe intern string of s and s2 are always the same
System.out.println(s.intern() == s2.intern()); // prints always true
}