Why does the String.intern() method return two different results?
String.intern() returns a String in the string literal pool. However if the string already exists in the pool, it will return the existing String.
If you pick a new String, it should return the String you created, but if you use a String which happens to exist in the pool already you will get the existing String.
It is reasonable to assume that in this case "java"
already exists in the pool so when you call intern() it returns a different object so ==
is false.
note: string.intern().equals(string)
should always be true.
The constant String
"java"
already exists in the Java constant pool, but you can verify that by changing
String str2 = new StringBuilder("ja").append("va").toString();
System.out.println(str2.intern()==str2);
to
String str2 = new StringBuilder("ja").append("va").toString();
System.out.println(str2.intern() == "java");
which will get the same constant and output
true
Alternatively, you could add "计算机软件"
and "String"
to the constant pool like
String a = "计算机软件";
String b = "String";
String str1 = new StringBuilder("计算机").append("软件").toString();
System.out.println(str1.intern() == str1);
String str3 = new StringBuilder("Str").append("ing").toString();
System.out.println(str3.intern() == str3);
Then you would get (consistent with your observations)
false
false