The difference between string new and direct assignment in Java

Source: Internet
Author: User

String str1= "abc"; and String str2 = new String ("abc"); What's the difference.

String str1= "ABC" might create an object or not create an object, and if the string "ABC" does not exist in the Java string pool, it will create a string object ("abc") in the Java string pool. If it already exists, STR1 direct reference to the object in this string pool.

String str2 = new String ("ABC") creates at least one object, or perhaps two. Because the new keyword is used, a str2 string object is created in the heap, and its value is "ABC". Also, if the string "ABC" does not exist in the Java string pool, it creates a string object in the Java string pool (" ABC ").

String has a intern () method, native, used to detect whether the string exists in the string pool.

Consider the following question:

String str1 = new String ("ABC");
String str2 = new String ("ABC");

STR1 = = is the value of str2 true or false? False.

String STR3 = "ABC";
String STR4 = "ABC";

String STR5 = "A" + "BC";

STR3 = = is the value of STR4 true or false? True.

STR3 = = is the value of STR5 true or false? True.

When writing code, generally do not string str2 = new String ("ABC");

String a = "ABC";
String b= "AB";
String c=b+ "C";
System.out.println (A==C); False
Both A and B are string constants, so they are determined at compile time!

A b in C is a reference not a string constant, so it is not determined at compile time.
And the string is final! So when the B + "C" is actually a new object created, then the reference to the newly created object is passed to C.

This article from Csdn Blog, reproduced please indicate the source: http://blog.csdn.net/kkdelta/archive/2009/03/02/3948725.aspx

The writing is really very detailed, worth learning!

The difference between string new and direct assignment in Java

Related Article

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.