The java String is an unchangeable class. To improve efficiency, java provides a String pool for the String class.
When we assign values to a String using code such as String s = "abc", JVM first checks whether the String constant pool contains the String "abc, if yes, the address is directly assigned to s. If no, a string object "abc" is created in the Stirng pool and its address is assigned to s.
Here, s is the reference of the object "abc", which can be understood as the address of the object.
For example:
public static void main(String[] args) { String s1="hello"; String s2="hello"; String s3="he"+"llo"; System.out.println(s1==s2); System.out.println(s2==s3);}
In the preceding Code, when String s1 = "hello" is executed, JVM creates a "hello" object in the String pool. When String s2 = "hello" is executed, because "hello" already exists in the String pool, the compiler directly assigns the "hello" address to s2. Therefore, s1 and s2 point to the same object, so the output is true. The same applies to S3.
Note: When using String s = new String (""); in this form of value assignment, two objects are actually generated.
For example: String s = new String ("abc"), a "abc" object is first generated in the String constant pool, and then new String () the heap allocates memory space and copies the "abc" in the constant area to the String object in the heap. Therefore, this code generates two objects, one in the constant area and the other in the heap area.
For example:
public static void main(String[] args) {String s1="hello";String s2=new String("hello");System.out.println(s1==s2);}
Here s1 points to "hello" in the constant area, s2 points to "hello" in the heap, so the output is false.