package com.zhb.jvm;
/**
*
* @author zhb
*
*/
public class RuntimeConstantPoolOOM {
public static void main(String[] args){
String str1 = "abc";
System.out.println(str1.intern() == str1); //true
String str2 = new String("abcd");
System.out.println(str2.intern() == str2); //false
String str3 =new StringBuilder("math").append("analyze").toString();
System.out.println(str3.intern() == str3); //true
String str4 =new StringBuilder("computer").append("software").toString();
System.out.println(str4.intern() == str4); //true
String str5 =new StringBuilder("jav").append("a").toString();
System.out.println(str5.intern() == str5); //false
}
}
First of all,we can know the definiton of the intern() method. Definition for intern : When the intern method is invoked, if the pool already contains a string equal to thisString object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, thisString object is added to the pool and a reference to this String object is returned.
str1.intern == str1 is true. this is easy to understand. str2.intern() == str2 this is also easy to understand by the definition of the method. But why str3.intern() == str3 is true.in fact,I think it is false by the definition. There is a opposite thing that str5.intern() == str5 is false. I run the command in the terminal java -version java version "1.7.0_40" Java(TM) SE Runtime Environment (build 1.7.0_40-b43) Java HotSpot(TM) 64-Bit Server VM (build 24.0-b56, mixed mode)
I want to acquire the correct answer.thank you very much!