Home >Java >javaTutorial >Comparative analysis of the differences between Java String and new String()
This article mainly introduces relevant information about the difference between Java String and new String(). Friends who need it can refer to it
The difference between Java String and new String()
The stack area stores references and basic types, but cannot store objects, while the heap area stores objects. == compares addresses, and equals() compares object contents.
String str1 = "abcd" implementation process: first create a str reference in the stack area, and then find its pointer in the String pool (which exists independently of the stack and heap and stores invariables) The object whose content is "abcd", if there is no one in the String pool, create one, and then str points to the object in the String pool. If there is, then directly point str1 to "abcd""; if the string variable str2 is later defined = "abcd", then the str2 reference will directly point to the "abcd" that already exists in the String pool, and the object will not be re-created; when str1 is assigned (str1 = "abc"), str1 will no longer point to "abcd". Instead, it re-points to "abc" in the String pool. At this time, if you define String str3 = "abc" and perform str1 == str3 operation, the return value is true, because their values are the same and the addresses are the same, but if the content is "abc" "str1 performs string + connection str1 = str1+"d"; at this time str1 points to the newly created object in the heap with the content "abcd", that is, str1==str2 is performed at this time, and the return value is false, because The address is different.
String str3 = new String("abcd") implementation process: Create the object directly in the heap. If there is String str4 = new String("abcd") later, str4 will not point to it. Instead of the previous object, create an object again and point to it, so if str3==str4 is performed at this time, the return value is false, because the addresses of the two objects are different. If it is str3.equals(str4), it returns true, because The content is the same.
No need to say more, just go to the code:
String str1 = "abcd"; String str2 = "abcd"; String str3 = new String("abcd"); String str4 = new String("abcd"); System.out.println(str1==str2);//true地址一样 System.out.println(str3==str4);//false,但地址不一样 System.out.println(str3.equals(str3));//true,值一样 System.out.println(str2.equals(str3));//true,值一样 System.out.println((str1+"a")==(str2+"a"));//false;进行了+连接地址不一样
The above is the detailed content of Comparative analysis of the differences between Java String and new String(). For more information, please follow other related articles on the PHP Chinese website!