Difference between creating a String object with quotes in Java and using Constructors

Source: Internet
Author: User

You can create a String object in either of the following ways:

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

What are the differences between the two methods? We can use the following two small examples to illustrate.



Example 1:

String a = "abcd";String b = "abcd";System.out.println(a == b);  // TrueSystem.out.println(a.equals(b)); // True
Here, a = B is true because both a and B reference the same string literal value in the Method Area. In java, when the same string literal value appears multiple times, only one copy of the string is saved in the memory, that is, the "abcd" that a points to and the "abcd" that B points to are the same object in the memory. This method is called "string interning )".


Example 2:

String c = new String("abcd");String d = new String("abcd");System.out.println(c == d);  // FalseSystem.out.println(c.equals(d)); // True

We know that the new operator is used to create a new object in the heap memory. As a result, two new objects will be created in the heap. Although their nominal values are the same, they are actually two identical objects, occupying two spaces. Therefore, c = d will naturally return false. The figure is as follows:



In addition, we can call the intern () method of String to force the JVM to use String resident. For example, the following code:

String c = new String("abcd").intern();String d = new String("abcd").intern();System.out.println(c == d);  // Now trueSystem.out.println(c.equals(d)); // True

When calling the intern () method, the system first checks whether there is "abcd" in the String constant pool ". equals (string in the constant pool) is a true object. If yes, this object is returned. If no, an "abcd" object is created and put in the constant pool. Therefore, when you create d, intern () directly returns the reference of the previously created "abcd.

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.