Java String constant pool

Source: Internet
Author: User

The java String is an unchangeable class. To improve efficiency, java provides a String pool for the String class.

When we assign values to a String using code such as String s = "abc", JVM first checks whether the String constant pool contains the String "abc, if yes, the address is directly assigned to s. If no, a string object "abc" is created in the Stirng pool and its address is assigned to s.

Here, s is the reference of the object "abc", which can be understood as the address of the object.

For example:


public static void main(String[] args) {        String s1="hello";        String s2="hello";        String s3="he"+"llo";        System.out.println(s1==s2);        System.out.println(s2==s3);}   

In the preceding Code, when String s1 = "hello" is executed, JVM creates a "hello" object in the String pool. When String s2 = "hello" is executed, because "hello" already exists in the String pool, the compiler directly assigns the "hello" address to s2. Therefore, s1 and s2 point to the same object, so the output is true. The same applies to S3.




Note: When using String s = new String (""); in this form of value assignment, two objects are actually generated.

For example: String s = new String ("abc"), a "abc" object is first generated in the String constant pool, and then new String () the heap allocates memory space and copies the "abc" in the constant area to the String object in the heap. Therefore, this code generates two objects, one in the constant area and the other in the heap area.

For example:


public static void main(String[] args) {String s1="hello";String s2=new String("hello");System.out.println(s1==s2);}

Here s1 points to "hello" in the constant area, s2 points to "hello" in the heap, so the output is false.

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.