= = interpretation

The effect is different for the base type and the reference type ==, as shown below:

  • Basic type: compares whether the values are the same;
  • Reference type: Compares whether references are the same;

Code examples:

String x = "string";
String y = "string";
String z = new String("string");
System.out.println(x==y); // true
System.out.println(x==z); // false
System.out.println(x.equals(y)); // true
System.out.println(x.equals(z)); // true

Copy the code

Since x and y refer to the same reference, == is also true, while the new String() method overwrites the memory space, so == is false, and equals always compares values, so it is true.

Equals reading

Equals is essentially equal to ==, except that String and Integer and others have overridden the equals method to make it a value comparison. Take a look at the code below.

First, equals compares an object with the same value by default, as follows:

class Hero {
    public Cat(String name) {
        this.name = name;
    }

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Hero h1 = new Hero("吕布");
Hero h2 = new Hero("Zhaoyun");
System.out.println(c1.equals(c2)); // false

Copy the code

The output is false to our surprise. Equals equals equals equals equals equals equals equals equals equals equals equals equals equals

public boolean equals(Object obj) {
		return (this == obj);
}

Copy the code

Equals is essentially equal to ==.

Why do two strings with the same value return true? The code is as follows:

String s1 = new String("Kobe");
String s2 = new String("Kobe");
System.out.println(s1.equals(s2)); // true
Copy the code

Similarly, when we go to String equals, we find the answer as follows:

public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = value.length;
        if (n == anotherString.value.length) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = 0;
            while(n-- ! = 0) {if(v1[i] ! = v2[i])return false;
                i++;
            }
            return true; }}return false;
}

Copy the code

String overrides Object’s equals method, changing reference comparison to value comparison.

Summary: == is a value comparison for primitive types and a reference comparison for reference types; Equals by default is a reference comparison, but many classes override the equals method (String, Integer, etc.) to make it a value comparison, so in general equals compares whether the values are equal.