Question 2 Comparison Between String equals and "=", stringequals
"="Compare whether the object is the same, that is, whether the memory address is the same
"Equals in String"Content of the comparison object
"Equals in Object"If the equals method is not rewritten, it is equivalent to "="; if the object content is compared, the equals method must be rewritten, because in practical applications, the comparison of object content is mostly performed. (See question 1)
1 String s1 = "String"; 2 String s2 = "String"; 3 String s3 = new String ("String"); 4 String s4 = new String ("String "); 5 System. out. println (s1 = s2); // The result is true 6 System. out. println (s1 = s3); // The result is false. 7 System. out. println (s1.equals (s2); // The result is true 8 System. out. println (s1.equals (s3); // The result is true 9 System. out. println (s3 = s4); // The result is false10 System. out. println (s3.equals (s4); // The result is true.
For the String class, let's talk about the String pool. strings are classes with high usage in programs. To improve efficiency, strings are managed by "pools.
String s1 = "String"; this object is not in the heap, but in the String pool. When you create another variable, Sting s2 = "String";, the object is first found in the pool, if this string exists, it will not be created, but s2 will also point to that string, so s1 and s2 will point to the same object, so s1 = s2 is true;
When String s3 = new String ("String"); It is different. This is to force an object to be created in the heap space and does not point to the String pool, so s1 = s3 is false; but s1.equals (s3); is true; String s4 = new String ("String"); is to create another object in the heap space, s3 = s4 is also false; but s3.equals (s4); is true.