The
== sign compares values when comparing basic data types, but when using the == sign to compare two objects, it compares the address values of the two objects.
equals() In the case of overriding, the memory address is compared, but most classes in Java have overridden the equals() method, so the values are compared
String str1 = "abc"; String str2 = "abc"; System.out.println(str1.equals(str2)); System.out.println(str1 == str2);
In this case, true and true are returned, and the second = = also returns true:
Because the constant pool in the memory belongs to the method area. When str1 is created, there is no constant pool, so the object "abc" is created in the constant pool. When str2 is created, the constant It already exists in the pool, so it will be used directly when creating it for the second time, so the address is the same
If it is changed to
String str1 = new String("abc"); String str2 = new String("abc");
str1==str2, it will return false because two objects are created. , the address is different.
The above is the detailed content of Java development == and equals(). For more information, please follow other related articles on the PHP Chinese website!