String str1 = new StringBuilder("Computer").append("Software").toString(); System.out.println(str1.intern() == str1); String str2 = new StringBuilder("ja").append("va").toString(); System.out.println(str2.intern() == str2);
Running on different jdk produces different results.
The result of running on openjdk 1.8 is true/true.
I don't care about the different results of different jdk operations here, just talk about the mechanism of the String.intern() method.
new StringBuilder("Computer").append("Software")When this code is executed, it will generate 2 strings "computer" and "software" and put it into the string pool, so when "computer software".intern() is used, there is no character "computer software" in the string pool. String, according to the definition of intern(): if the string (equals) exists in the string pool, return the string reference in the string pool, if it does not exist, put the string (copy) into the string pool and return This string reference. So the result of str1.intern() == str1 is true.
When str2.intern(), the string "java" already exists in the string pool (the author Zhou Zhiming's explanation), so he said that the return result is false, but the return result on my machine is true, maybe in openjdk 1.8" java" This string does not exist in the string pool. Don't worry about this here.
String str1 = "str1";//The string constant is copied directly to the string pool System.out.println(str1.intern() == str1);//true String str2 = "str" + "2";//It will be optimized to "str2" at compile time System.out.println(str2.intern() == str2);//true String str3 = new String("str3");//At this time, "str3" is a string constant and has entered the string pool System.out.println(str3.intern() == str3);//false String str3_2 = new String("str") + new String("3"); System.out.println(str3_2.intern() == str3_2);//false; The above two strings str and 3 are constants, which have been put into the string pool, and "str3" is also in the string pool (see front str3 variable) String str4 = new String("str") + new String("4"); System.out.println(str4.intern() == str4);//true; this will not be explained String str5 = new StringBuilder("str5").toString();//"str5" is a string constant, which has been stored in the string pool System.out.println(str5.intern() == str5);//false; String str6 = new StringBuilder("str").append("6").toString(); System.out.println(str6.intern() == str6);//true; same as str4 variable
The above code runs on openjdk1.8.
It can also be viewed through javap decompilation, but I will not look at the jvm instruction yet, and I will study it later.