The difference between using string constants to assign values in Java and constructing a string object with new

Source: Internet
Author: User

" ABC "  New String ("ABC");

String str1 = "abc"; it is possible to create or not create an object, and if the string "ABC" does not exist in the Java string pool, it creates a string object ("abc") in Java string dominant. Then str1 points to this memory address, regardless of how many string objects in this way are later created with values of "ABC", there is always only one memory address assigned, followed by a copy of string, called "string Dwell" in Java, and all string constants will automatically reside after compilation.

String str2 = new String ("ABC"); At least one object can be created or two. Because the new keyword is used, a str2 string object will definitely be created in the heap, whose value is "ABC". At the same time, if the string does not exist in the Java string pool, it will create the string object "ABC" in Java dominant

String str1 =NewString ("ABC"); String str2=NewString ("ABC"); str1= = STR//falseString STR3="ABC"; String STR4="ABC"; String STR5="AB"+"C"; STR3= = STR4//trueSTR3 = = STR5//trueString a="ABC"; String b="AB"; String C= B +"C"; System. out. println (A = = c);//false

A, B is determined at compile time, and C is a reference variable and is not determined at compile time.

Application: Recommended in peacetime use, try to use string = "ABCD", this way to create a string, rather than string = new string ("ABCD"), this form, because using the new constructor to create a string object will certainly open up a new heap space , while double quotes are optimized using string interning (String dwell), which is much more efficient than the constructor.

Reference: 1. The difference between string assignment in Java and use of new

The difference between the string class in 2.Java and the direct assignment string through new

The difference between using string constants to assign values in Java and constructing a string object with new

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.