[Elaborate on Java] (3) Does the & quot; or constructor be used to create a string?

Source: Internet
Author: User

[Elaborate on Java] (3) Do I use "" or constructor to create a string?
In Java, you can create strings in two ways:

String x = "abc";String y = new String("abc");
What are the differences between the two methods (double quotation marks, constructor?
1. Double quotation marks vs Constructor
You can use these two simple code instances to answer this question:
Instance 1
String a = "abcd";String b = "abcd";System.out.println("a == b : "+(a == b)); // trueSystem.out.println("a.equals(b) : "+(a.equals(b))); // true
A = B is equal to true because x and y point to the same String constant in the method area, and the memory reference is the same.
When the same String constant is created multiple times, only one copy of the String constant is saved, which is called "string resident ". In Java, all string constants reside during compilation.
Instance 2
String c = new String("abcd");String d = new String("abcd");System.out.println("c == d : "+(c == d)); // falseSystem.out.println("c.equals(d) : "+(c.equals(d))); // true
C = d is equal to false because c and d point to different objects in the heap. Different objects have different memory references.
The following figure demonstrates the above conclusions.
2. The runtime string resident
The runtime will also contain strings, even if the two strings are created by the constructor method.
String c = new String("abcd").intern();String d = new String("abcd").intern();System.out.println("c == d : "+(c == d)); // trueSystem.out.println("c.equals(d) : "+(c.equals(d))); // true    (JDK1.7)
If the nominal value "abcd" is already of the string type, the constructor will only create an additional unused object. Therefore, if you only need to create a string, you can use double quotation marks. If you need to create a new object in the heap, you can choose the constructor method.

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.