1. = =
== compares the values in the stack
- Basic data types that directly compare variable values for equality;
- Reference type, which compares the variable to the address of the memory object
2, equals
- The equals method in Object also compares equals by default, and is usually overridden
public boolean equals(Object obj) {
return this == obj;
}
Copy the code
-
If the equals method is not overridden, it compares the address of the object to which the variable referring to the type refers
-
A class like String overrides equals to compare the contents of the objects to which it refers
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj instanceof String) {
String s = (String)obj;
int i = value.length;
if (i == s.value.length) {
char ac[] = value;
char ac1[] = s.value;
for (int j = 0; i-- ! =0; j++)
if(ac[j] ! = ac1[j])return false;
return true; }}return false;
}
Copy the code
3, test,
public class test {
public static void main(String[] args) {
String s1 = "hello"; // Create a new object in the string constant pool
String s2 = "hello"; // "Hello" was found in the string constant pool, pointing to the object address
String s3 = new String("hello"); // Create a new object in the heap and point to its address
System.out.println(s1 == s2); //true
System.out.println(s1 == s3); //false
System.out.println(s1.equals(s2)); //true
System.out.println(s1.equals(s3)); //true }}Copy the code