The difference between two ways of assigning strings in Java

Source: Internet
Author: User

This article was modified on: https://www.zhihu.com/question/29884421/answer/113785601

Preface: In Java, there are two kinds of assignment of string, the first is by " literal " assignment, such as: string str= "Hello", the second is to create a new object with the keyword, such as: string str=new String ("Hello"). So what's the difference between the two ways of assignment, and here's a concrete analysis.

1. First review the structure diagram of the Java Virtual machine.

In the above virtual machine structure diagram, the middle of the multicolored area is called the "runtime data area (Run-time areas)". The memory that is managed by the virtual machine is the "memory" of plain English. One of the last two, the program counter (PC registers) and the local method stack (Native) is OK with what is said, first ignore. Generally speaking, the most important thing about virtual machine memory is the following three blocks:

1) Heap: The largest chunk of space. holds object instances and Arrays . Global share.

2) Stack: Full name "virtual machine stack (JVM Stacks)". store basic types, and object references. Thread Private .

3) Method Area: The " class" is loaded with information, constants, and static variables stored here. Global share. In the hotspot is also called "Eternal Life Generation". But the two cannot be equated.

2. Stacks, heaps, and non-heaps.

"local variables table" "operand stack (Operand stack)" thread-private , each method is executed with a " tack Frame) " local variable table and operand stack . The base data type and object reference exist in the stack, but there is a local variable table. And the operand stack is the actual operating station of the thread.

For example, to do an addition 100+98, the local variable table is the place where the data is stored, has been unchanged, until the addition done and added in. The operation of the stack is very busy, first put two numbers in, and then Sum, calculate out later to bounce out.

The middle of this non-heap (non-heap) can be roughly understood as the non-heap contains the eternal generation, and the eternal generation includes the method area. It says that after each class is loaded, the information for the class exists in the method area . The most relevant to string is the " "string Chang (String Pool)" Span class= "Html-tag" > globally shared . The position is interned the position of the string in the second picture, which can be understood as being outside the method area in the eternal life generation. Later on, the String.intern () method, after which the string resides, is placed in the string Pool.

3. Specific Analysis

As in the following Test.java file, the main thread method in main declares that a literal is "Hello" to the string str.

 1  package   com.test.java.string;  2  class   test{ 3  public  void   F (String s) {...};  4  public   Static  void   main (string[] args) { Span style= "COLOR: #008080" >5  String str = "Hello" ;  6   ...  7  }  8  }

After compiling to the Test.class file, for example, in addition to the version, field, method, interface and other descriptive information, there is also called "Chang (Constant Pool Table)" Something (light green block). However, this constant pool is not the same as the constant pool in memory. The constant pool in the class file mainly consists of two things:"literal (Literal)" and "symbolic reference amount (symbolic References)". The literal includes some constants defined in the class, because the string is immutable and is decorated with the final keyword, so the "Hello" string in the code is written as literal (constant) in the constant pool of class.

Run the program used to Test class, the information for the Test.class file is parse into memory in the method area . In the class file, most of the data in the constant pool is loaded into the run-time pool. But string is not. A reference to "Hello" in the example is stored in the string Chang, which is also in the non heap. The "Hello" ontology, like all objects, is created in the heap area. in the http://rednaxelafx.iteye.com/blog/774673 article, the test results are in the new generation of Eden area. But since there is always a reference residing in the string constant pool, it will not be cleaned up by the GC. This Hello object will survive to the end of the entire thread. As shown, the exact position of the string constant pool is in the past said Eternal generation, outside of the method area.

Note: This is only the case when the test class is loaded by the ClassLoader. The STR variable in the main thread is not created at this time, but the instance of Hello is already in the heap, and the reference to it is already in the string constant pool.

When the main thread starts to create the STR variable, the virtual machine will look in the string constant pool to see if there is a string that equals ("Hello"). If found, the STR variable is created in the local variable table of the current stack frame of the stack, and the reference to the Hello object in the string constant pool is copied to the STR variable. If it is not found, the object is recreated in the heap and the reference resides in the string constant area. Then copy the reference to the local variable table of the stack frame.

If we had defined a number of strings with the value "Hello" at that time, such as the following code, there were three variables str1,str2,str3, and no string instances were added to the heap. The local variable table three variables uniformly point to the same heap memory address.

1  Packagecom.test.java.string;2 classtest{3       Public voidF (String s) {...};4       Public Static voidMain (string[] args) {5String str1 = "Hello";6String str2 = "Hello";7String STR3 = "Hello";8          ...9      }Ten}

Between the STR1,STR2,STR3 can be connected with = =.

But if you use the New keyword to create a string, the situation is different.

1  Packagecom.test.java.string;2 classtest{3          Public voidF (String s) {...};4          Public Static voidMain (string[] args) {5String str1 = "Hello";6String str2 = "Hello";7String STR3 =NewString ("Hello");8             ...9         }Ten}

At this time, str1 and str2 are still the same as before. But STR3 because the new keyword requests a new piece of memory in the heap heap to create an object. Although literally "Hello", but completely different objects, there are different memory addresses.

Of course the String#intern () method allows us to manually check the string constant pool and place the string addresses with the new literals in the constant pool.

Finally, JDK 7 begins with hotspot moving interned string from PermGen to heap, and JDK 8 completely cancels the PermGen. But anyway, the fundamentals are still the same.

Summary: Through the above analysis, it can be very clear to find the difference of two kinds of assignment of string, each reading has a lot of income.

by Shawn Chen 2018.3.20, PM.

The difference between two ways of assigning strings in Java

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.