[Original] personal understanding of the Java string pool, please give pointers !!

Source: Internet
Author: User

String A = new string ("ABC ");
String B = "ABC ";
String c = new string ("ABC ");
Question: A String object is created in total?

Understanding about the string pool:
String A = new string ("ABC"); how many objects are created in total? 2

Running sequence:
1. Because it is a new string (), we need to create a new space in the heap.
2. Search for objects with the same value as ABC in the pool. Because no, create an ABC object in the pool!
3. Copy the objects in the pool to the heap, create an object in the heap, and return the reference address of the heap to A. A is not an object,

Only the returned address variables are stored.

String B = "ABC"; no zero objects are created

First, this expression does not use the New Keyword, so it does not open up space in the heap, but directly de-Words

Search for keys with the same data in the string pool. If yes, return the reference address of this key,

Two strings point to the address of the string pool! If not, create an object directly in the string pool! And

Return address. This creates a String object that is irrelevant to the heap zone!
 
String c = new string ("ABC"); an object is created this time! 1

First, find this value in the string pool. If no value exists, create it because it is already in

The object is created in the string pool.

New String () and copy this object to create a new object in the heap!
Therefore, you can create an object in the string pool instead of directly creating an object in the heap! Institute

It is!

String d = B + "ABC"; there is a string reference at this time, so create a space in the heap and save the value,

Summary: when creating a string, you must first search for it in the string pool. If not, create a string, as shown in figure

If yes, do not create it!

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.