Two types of value assignment Analysis of the String class

Source: Internet
Author: User

Two types of value assignment Analysis of the String class

1. String constant pool

2. String name = new String ("hello ");

3. String name = "hello ";

Structure of the analysis object in memory:

Constant pool -- used to store strings

Hello -- constant; name -- Variable

Every time a new object is created, an object is generated in the heap, And the pointer in the stack points to the heap. Hello, It is the value stored in heap memory. The "hello" string will be checked in the String constant pool, check whether the constant "hello" exists in the "String constant pool"-if not, the string "hello" will be saved to the "String constant pool.


String s1 = new String ("hello ");

String s2 = "hello"; // you can create a maximum of one String object. You may not need to create an object.

In summary, when s1 creates an object in the new string -- "hello" in the heap, it then saves "hello" to the String constant pool. (The String constant pool is in the heap memory)

Frequently Asked Questions during interviews:

String s1 = new String ("hello"); how many objects are created?

The answer is: two -- one is in the heap memory, and the other is in the constant pool.

1. Create a new value in the heap. 2. Store "hello" in the String constant pool. For the next time you use the same value, the new value will be found in the constant pool.

2. There is a benefit for the shorthand Method -- it will directly let s2 look for it in the constant pool to see if there are the same values, yes, direct to; no, A "hello" will be created in the constant pool, and s2 will point to "hello ".


Related Article

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.