Comparison and difference between Java String and new String of

  • 2020-07-21 08:00:37
  • OfStack

The difference between Java String and new String()

The stack blocks references and primitive types, objects cannot be stored, while the heap blocks objects. == is the comparison address, equals() compares object content.

String str1 = implementation of "abcd" : first, the stack area creates str references, then look for objects in String pool (independent of stack and heap, storage is not variable) that point to "abcd". If there is no object in String pool, then create 1 object. Then, str points to the object in String pool. If the string variable str2 = "abcd" is later defined, then str2 is directly referred to the "abcd" that already exists in the String pool, and the object is not recreated. When str1 is assigned (str1= "abc"), str1 will no longer refer to "abcd", but to "abc" in the String pool. At this point, if String str3 = "abc" is defined, str1 == str3 is performed, and the return value is true because they have one value and one address. But if str1 with content of "abc" concatenates the string str1 = str1+"d"; At this time, str1 points to the object newly created in the heap with the content of "abcd", that is, str1==str2, return value false, because the address is not one.

String str3 = new String("abcd") : Create objects directly in the heap. If there is String str4 = new String("abcd"), str4 does not point to the previous object, but recreates an object and points to it. So if str3==str4, the return value is false because the addresses of the two objects are not the same. If str3.equals (str4), the return value is true because the contents are the same.

Without further ado, code directly:


String str1 = "abcd";
String str2 = "abcd";
String str3 = new String("abcd");
String str4 = new String("abcd");
System.out.println(str1==str2);//true address 1 sample 
System.out.println(str3==str4);//false, But the address is not 1 sample 
System.out.println(str3.equals(str3));//true, value 1 sample 
System.out.println(str2.equals(str3));//true, value 1 sample 
System.out.println((str1+"a")==(str2+"a"));//false; the + Connection address is not 1 sample 

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: