On the intern () method of string class in Java

String s1 = new StringBuilder(” Go “).append(” od “).toString();
System.out.println(s1.intern() == s1); String s2 = new
StringBuilder(” ja “).append(” va “).toString(); String s2 = new
StringBuilder(” ja “).append(” va “).toString();
System.out.println(s2.intern() == s2); Output is true or false
in the search on the net, have explained string constants in the pool a Java this string constants, and so the example below would be false.

String sb =new StringBuilder(” Go “).append(” OD “).toString();
String sb =new StringBuilder(” Go “).append(” OD “).toString();
String s1 = new String(” Good “);
System.out.println(sb.intern()==sb);
returns false!!
originally used in intern method, will first judgment in the constant pool have the corresponding string, have put the string, not words

The intern() implementation in JDK 1.7 does not copy the instance any more, it just records the instance reference that first appears in the constant pool, so the reference returned by the intern() is the same as the instance of the string created by the StringBuilder


Read More: