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.