Simple Java String (medium)
Read the original 1. Preamble
In the previous article, we introduced the constituent elements of a string object in Java, the differences between 2 kinds of creation, and the different manifestations in memory regions. The last question left was the difference between the Intern method of string in different JDK versions. This article mainly discusses the problems brought by the intern () method. 2. Intern method 2.1. API Introduction
First look at the official API description:
When the intern was invoked, if the pool already contains a string equal to this {@code string} object as determined By the {@link of #equals (Object)} method, then the ' string from the ' pool is returned. Otherwise, this {@code string} object are added to the pool and a reference to this {@code String} object is returned.
When the Intern method is invoked, if the object is present in the string constant pool, the constant pool is returned, and if not, the constant pool is added and returned. 2.2. JDK Version Issue
Let's look at a piece of code:
Code 1:
String str1 = new String ("Hello");//create several objects. Answer 2
String str2 = Str1.intern ();
System.out.println (str1 = = str2); Jdk1.6:false,jdk1.7:false
//code 2:
String str3 = new StringBuilder ("he"). Append ("Llo"). ToString (); Several objects are also created at this time. Answer 1, not "he" and "Llo"
String STR4 = Str3.intern ();
System.out.println (STR3 = = STR4); Jdk1.6:false,jdk1.7:true
Next we analyze the difference in this result:
Code 1: str1 is new, that is, str1 points to heap memory, and STR2 is the Intern () method that invokes str1, that is, the str2 points to the constant pool, so the result is JDK1.6 str1 in!=, 1.7 str2. Note that at this point, after the creation of the STR1, because new is the "Hello" as the initial value, so the constant pool will also create a "hello", so when the call to intern is a direct return of the constant pool reference.
Code 2: STR3 is created by stringbuilder#tostring (), and the inner implementation of StringBuilder is to use its value as the value of the string object. Then call Arrays.copyofrange replication, so there is no "hello" in this constant pool.
Read the full text