== : This is used to determine whether the addresses of two objects are equal. That is, determine whether two objects are the same object. (Base data type == compares values, reference data type == compares memory addresses).

Equals () : Also checks whether two objects are equal. There are two general use cases:

  1. Class not overriddenequals()Methods. byequals()Comparing two objects of this class is equivalent to comparing two objects by “==”.
  2. Class coversequals()Methods. We usually cover them allequals()Method to determine that the contents of two objects are equal; Return true if their contents are equal (that is, the two objects are considered equal).

For example:

public class test1 {
  public static void main(String[] args) {
    String a = new String("ab"); // a is a reference
    String b = new String("ab"); // b is another reference, the object has the same content
    String aa = "ab"; // Put it in the constant pool
    String bb = "ab"; // Search from the constant pool
    if (aa == bb) // true
      System.out.println("aa==bb");
    if (a == b) // false, different object
      System.out.println("a==b");
    if (a.equals(b)) // true
      System.out.println("aEQb");
    if (42= =42.0) { // true
      System.out.println("true"); }}}Copy the code

Description:

  • The superclass Objectequals()The method is the memory address of the object being compared; String rewrite theequals()This method compares the values of objects.
  • When creating an object of type String, the virtual machine looks in the constant pool for an existing object with the same value as the object to be created, and assigns it to the current reference if it does. If not, create a new String in the constant pool.