Two different ways to create a string class
" Zheng " New String ("junxiang"); Second method of Creation
The first is to create the object in the constant pool at compile time, and if the string object "Zheng" already exists in the constant pool, the address is assigned to S1. The second way to create this is to create the object in the heap at run time, and recreate an object regardless of whether it is present in the heap.
New String ("xyz"new string ("xyz" );
The top creates 3 string objects, the compile-time constant pool creates 1, and 2 is created in the run-time heap.
Example 1:
String S1 = "xyz"= "xyz"; System.out.println (S1==s2);
The output is true because if the same object is already in the constant pool, it is no longer created and the address is assigned to S2.
Example 2:
New String ("xyz"new string ("xyz"= = s2);
The output is false because a new object is created each time the heap is taken with new.
Example 3:
String x = "Zheng"= "JX"= "Jxzheng"= y += "JX" + "Zheng"= = = s); //Output False because there are variables in the string connection operand. So the runtime can be determined and exists in the heap. System.out.println (s2 = = s);//Output True because the string join operand is a string constant, which can be determined at compile time, in the presence of a constant pool.
The following four rules are summarized:
1, the string created by using the quotation marks alone is a constant, and the compilation period is determined to be stored in the string pool;
2, objects created with the new String ("") are stored in the heap and are newly created at run time;
3, using a string connector that contains only constants, such as "AA" + "AA" created is also a constant, the compilation period can be determined, has been determined to store in the string pool;
4, the object created by using a string connector containing a variable, such as "AA" + S1, is created at run time and stored in the heap;
String.intern ()
New String ("xyz"= S1.intern (); Intern () returns a reference to this string object in the constant pool. If the string object already exists in the constant pool, the reference to the object is returned directly, otherwise the object is created in the constant pool and the reference is returned.
Example 4:
New New String ("2"); S3.intern ();
= = S4); //JDK7/8 output is true
The reason is that the constant pool in jdk7 is not in the method area but in the heap, and you can store the object's reference directly. So S4 and S3 point to the same object. This blog String.intern () Test of JDK6 and JDK7 is relatively clear.
Reference blog:
A summary of the constant pool of string
Java stacks and constant pools
Java constant pool Comprehension and summary
Java constant Pool Detailed questions
Java Constant Pool Understanding