Java string constant pool

Source: Internet
Author: User

String S1 = "Hello"; String S2= "Hello"; String S3= "Hel" + "Lo"; String S4= "Hel" +NewString ("Lo"); String S5=NewString ("Hello"); String S6=S5.intern (); String S7= "H"; String S8= "Ello"; String S9= s7 +S8; System.out.println (S1= = s2);//trueSystem.out.println (S1 = = S3);//trueSystem.out.println (S1 = = S4);//falseSystem.out.println (S1 = = S9);//falseSystem.out.println (S4 = = S5);//falseSystem.out.println (S1 = = S6);//true

At the beginning of the string, often see a similar problem, it will inevitably be somewhat puzzled, see the answer always refer to the string constant pool, run constant pool concepts, it is easy to confuse people.

Here's how the string in Java is created.

There are two ways to assign a string, the first of which is to assign a value by literal .

String str = "Hello";
The second type is throughNewKeyword to create a new object.
New String ("Hello");

To figure out the difference between these two ways, first know where they are stored in memory.

Our usual memory is the runtime data areain the graph, where the creation of the string is related to the method area, the heap area , and Stack area.

    1. method Area : Stores class information, constants, static variables. Global share.
    2. Heap Area : Holds objects and arrays. Global share.
    3. stack : Basic data types, object references are stored here. Thread Private.

Whenever a method is executed, a stack frameis created in the stack, and the base data type and object reference exist in the stack frame local variable table (local Variables).

When a class is loaded, the class information is stored in a non-heap method area. In the method area, there is a block called the runtime Constant pool, which is private for each class, and the "constant pool" in each class file is loaded by the loader after the load is stored here, which is explained later.

The string pool, which is most relevant to strings, is positioned at the location of the interned Strings above the method area, and has been mixed with the run-time constant pool. In fact, there are two completely different storage areas, and the string constant pool is shared globally. When a string calls the String.intern () method, its reference is stored in the string pool.

Knowing these concepts, here's how the two types of string creation differ.

The following test class assigns the string str a "Hello" in the Main method, with the literal value assigned to it.

 Public class  Test {    publicstaticvoid  main (string[] args) {                = "Hello";            } }

Test.java files are compiled with a. class file that contains information about the class, including a section called Chang (Constant Pool) , and A. class constant pool and a constant pool in memory is not a thing.

The. class file constant pool is primarily stored as literals , literals include constants defined in the class, because string is immutable (why is the string immutable?). ), so the string "Hello" is stored here.

When the program uses the Test class, Test.class is parsed into the in-memory method area. The constant pool information in the. class file is loaded into the run-time-constant pool, but string is not.

In the example, "Hello" creates an object in the heap and holds a reference to it in the string pool, as shown in.

At this point only the test class has just been loaded, and STR in the main function has not been created, and the "Hello" object has been created in the heap.

When the main thread starts to create the STR variable, the virtual opportunity goes to the string pool to find if there is a string of equals ("Hello"), and if it is equal, copies the reference to "Hello" in the string pool to Str. If no equal string is found, a new object is created in the heap, the reference resides in the string pool, and the reference is assigned to Str.

When you create a string by literal assignment, no matter how many times it is created, as long as the string has the same value, they point to the same object in the heap.

 Public class Test {    publicstaticvoid  main (string[] args) {                = "Hello";        = "Hello";         = "Hello";            } }

When you use the new keyword to create a string, the previous process is the same, but at run time, regardless of whether there is an object reference equal to the current value in the string pool, a new piece of memory is created in the heap, creating an object.

 Public class Test {    publicstaticvoid  main (string[] args) {                = "Hello";        = "Hello";         New String ("Hello");}            }

Now let's look back at the previous example.

String S1 = "Hello"; String S2= "Hello"; String S3= "Hel" + "Lo"; String S4= "Hel" +NewString ("Lo"); String S5=NewString ("Hello"); String S6=S5.intern (); String S7= "H"; String S8= "Ello"; String S9= s7 +S8; System.out.println (S1= = s2);//trueSystem.out.println (S1 = = S3);//trueSystem.out.println (S1 = = S4);//falseSystem.out.println (S1 = = S9);//falseSystem.out.println (S4 = = S5);//falseSystem.out.println (S1 = = S6);//true

With the above foundation, the previous problem is solved.

S1 also creates a reference to its object in the string pool while the object is being created.

Since S2 is also created using the literal, it will go to the string pool to find out if there is an equal string, obviously S1 has helped him to create, it can directly use its reference. So s1 and S2 all point to the same address, so s1==s2.

S3 is a string concatenation operation, the part that participates in stitching is literal, the compiler optimizes, and at compile time S3 becomes "Hello", so s1==s3.

Although S4 is also a concatenation, "Lo" is created by the new keyword and cannot be known at compile time, so it cannot be optimized like S3. So you have to wait until the runtime to determine that the address of the new object must be different from the previous.

Similarly, theS9 is spliced by two variables, and the compilation period does not know their exact location and does not make optimizations.

S5 is new, and the address in the heap must be different from S4.

S6 uses the Intern () method to get the S5 reference to the string pool, not the address of the S5 itself. Because their references in the string pool point to the same "Hello" object, natural s1==s6.

To summarize:

    • The literal creation of the string is first found in the string pool to see if there are equal objects, no words are created in the heap, the addresses reside in a string pool, and some are directly referenced in the pool, avoiding the repetition of creating objects.
    • When the new keyword is created, the preceding action is the same as the literal creation, except that a new object is created at run time and the variable refers to the address of the new object.

Resources:

https://www.zhihu.com/question/29884421/answer/113785601

Http://www.cnblogs.com/iyangyuan/p/4631696.html

http://blog.csdn.net/sugar_rainbow/article/details/68150249

Java string constant pool

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.