recently, I have been studying some basics. I have seen the constant pool and String.intern
method in Java. I have also found some sample code on the Internet to run on my own machine, but I have found a strange problem, such as the following code:
// -sharp0
String str1 = new String("0") + new String("0");
str1.intern();
String str2 = "00";
System.out.println(str1 == str2); // true
System.out.println(str1.equals(str2)); // true
// -sharp1
String str1 = new String("1") + new String("1");
str1.intern();
String str2 = "11";
//
System.out.println(str1 == str2); // false
// hashCode
System.out.println(str1.hashCode() == str2.hashCode()); // true
System.out.println(str1.equals(str2)); // true
// -sharp2
String str1 = new String("2") + new String("2");
str1.intern();
String str2 = "22";
System.out.println(str1 == str2); // true
System.out.println(str1.equals(str2)); // true
I don"t understand why when two new String ("1") + new String ("1")
add variables intern
, defining the same string
will not point to the address in StringPool
!
the above code -sharp1
is changed to write as follows:
// -sharp1-Update
String str1 = (new String("1") + new String("1")).intern();
String str2 = "11";
System.out.println(str1 == str2); // true
System.out.println(str1.equals(str2)); // true
can also find the corresponding citation in StringPool
. This is a strange thing. Please give me some advice!