Is doing:
String a = new String();
String b = a;
and doing:
String a = new String();
String b = a.intern();
is the same ?
Actually, the reference are all the same if I test:
String a = new String("te");
String b = a.intern();
String c = a;
String d = "t" + "e";
System.out.print(a.equals(b));
System.out.print(b.equals(c));
System.out.print(a.equals(d));
Cause the String will ever be in the String pool ?
Your
equalstests aren’t checking for references – they’re checking for string equality. You should be using==to check the references for identity. Effectively, you’re making the common rookie Java mistake in reverse – usually people use==when they should be usingequals. In this particular case, all of those will printfalse, because there are two String objects involved (the string from the constant pool, and the new string created in the first line). If we call these #1 and #2 respectively, we end up with:However, you may find this interesting:
"te"and"t" + "e"are equal constant string expressions, so end up as references to a single string, and callinginternon a string already in the literal pool won’t have any effect.