Does string literals in Java automatically generate a string object? __java

Source: Internet
Author: User

In the development process, it is often necessary to write directly a string variable, that is, double quotes include character data, such a literal string, whether a string object has been created. If not, where is the data stored? If there is, there is no new statement Ah, how to create it.

Look at the following code:

String str1= "abc";//Create an ABC string object

String Atr2=new string ("abc");//Create an ABC string object with the new statement

In the code above, we created the string variable str1 and str2 in two ways, what's the difference? In fact, when the Java Virtual Machine (JVM) executes this code, it encounters the double quotation mark operator, which automatically creates a string object. The string object represents ABC, and then returns a reference to that object.

For the STR1 string, its creation process is as described above. Before the object is created, the JVM searches the string object pool for whether the character object has been created, or if it has been created, returns a reference directly, otherwise the return reference is created first.

Instead of str2 a string variable, the creation process requires one more step. In addition to the STR1 string object creation process, it creates a new string object, which is the function of the new keyword, and returns a reference to STR2.

Although the values for STR1 and str2 are the same, their references are different, meaning that the return value of the code is false.

str1=str2;//result 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.