From the javaDocs of String class's 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.
Consider the following use-cases:
String first = "Hello";
String second = "Hello";
System.out.println(first == second);
String third = new String("Hello");
String fourth = new String("Hello");
System.out.println(third == fourth);
System.out.println(third == fourth.intern());
System.out.println(third.intern() == fourth);
System.out.println(third == fourth);
System.out.println(third.intern() == fourth.intern());
System.out.println(third.intern() == first);
String fifth = new String(new char[]{'H','e','l', 'l', 'o'});
String sixth = new String(new char[]{'H','e','l', 'l', 'o'});
System.out.println(fifth == fifth.intern());
System.out.println(sixth == sixth.intern());
String seven = new String(new char[]{'H','e','l', 'l', 'o' , '2'});
String eight = new String(new char[]{'H','e','l', 'l', 'o' , '2'});
System.out.println(seven == seven.intern());
System.out.println(eight == eight.intern());
Can someone please explain why seven == seven.intern()
is true whereas the following are false:
System.out.println(fifth == fifth.intern());
System.out.println(sixth == sixth.intern());
System.out.println(eight == eight.intern());
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…