[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)); // true
System.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)); // false
System.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)); // true
System.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.