Java create string object mechanism string buffer pool string concatenation mechanism

Source: Internet
Author: User

1.String str = new String ("Hello");

2 objects were created, 1. Check that there is no hello in the constant pool, no, create the object in the constant pool, and then create the object to be placed in the heap. If the constant pool has a Hello object, only one object is created and placed in the heap.

2. String constant pool in method area

3.String str = "Hello"; check that the constant pool has no hello, if any, then point to the object, and if not, create the object in the constant pool.

4.intern () method. Turn the string into a string in the constant pool: Returns the string if the constant pool already contains a string equal to the string object. Otherwise, the string object is added to the constant pool and the reference is returned.

5.String S1 = "Tom";

String s2 = "Cat";

String s3 = "Tomcat";//Creates an object in a constant pool.

String S4 = "Tom" + "cat"; object not created

String S5 = S1 + s2;//creates an object "tomcat"

S3 = = S4;true

S3 = = S5;false

6.1, String s= "a" + "B" + "C" + "D" created several objects (assuming the previous string pool was empty)//created an object, in a constant pool
2,stringbuilder sb = new StringBuilder ();
String a = "a";
String B = "B";
String c = "C";
String d = "D";
String s = a+b+c+d; This sentence creates several objects//creates 1 String objects, creating a total of 3 objects (new StringBuilder (), New Char[],new String ())
StringBuilder sb = new StringBuilder ();
Sb.append ("a"). Append ("B"). Append ("C"). Append ("D"); This sentence creates several objects//creates 0 string objects

7. String constant pool in the method area

Java create string object mechanism string buffer pool string concatenation mechanism

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.