2 Kinds of assignment analysis of String class

Source: Internet
Author: User

1. String constant Pool

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

3,String name = "Hello";

Analyze the structure of an object in memory:

Chang--Used to store strings

Hello--is a constant; name--is a variable

Whenever a new object is created, an object is generated in the heap, and the pointer in the stack points to the heap. Hello is a heap of memory stored in the value, will be "hello" this string into the string constant pool to check, see "string constant pool" There is a "hello" constant-if not, will be "hello" this string into the "string constant pool".


string S1 = new String ("Hello");

String s2 = "Hello"; Create at most one string object, possibly without creating an object

In summary, S1 in the new string, first create the object in the heap-"Hello", then, will "hello" to the string constant pool to save again. (The string constant pool is in heap memory)

interview Frequently asked:

string S1 = new String ("Hello"); create several objects?

The answer is: 2-- 1 is in heap memory, and the other is in a constant pool.

1, new 2 created in the heap, "Hello" exists in the string constant pool-for the next time with the same value, will be found from the constant pool.

2, shorthand method has a benefit-will directly let S2 to the constant pool to find, see if there is the same value, there, direct; no, create a "hello" in the constant pool, and then let S2 point to "hello."


2 Kinds of assignment analysis of String class

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.