==The difference and connection between and equals method

Posted by Sobbs on Thu, 28 Nov 2019 20:20:25 +0100

There are two ways to test whether two variables are equal in Java programs:
One is to use the = = operator, the other is to use the equals() method.
When = = is used to determine whether two variables are equal, if two variables are of basic type and both are of numerical type, true will be returned as long as the values of two variables are equal.
But for two reference type variables, = = returns true only if they point to the same object.
Because there is no call method for basic type variables, equality cannot be judged by equals() method.
But if you change the basic data type to a wrapper class, you can use the equals() method to determine equality.
When using the equals() method to determine whether two variables are equal, the rule similar to "equal value" does not strictly require two reference variables to point to the same object. For example, for two string variables, they only need to refer to the same character sequence contained in the string object to identify equality.
Note: the equals() method is an instance method provided by the Object class, so all reference variables can call this method to determine whether they are equal to other reference variables. For example, String has overridden the Object's equals() method.

public class TestDemo2 {
    public static void main(String[] args) {
        String s1 = "Insane Java";//Direct reference to "crazy Java" in constant pool
        String s2 = "Insane";
        String s3 = "Java";
        String s4 = "Insane"+"Java";//s4 is determined at compile time and also refers directly to the value in the constant pool.
        String s5 = new String("Insane Java");//References the newly created String object in heap memory.
        String s6 = "Insane"+new String("Java");
        String s7 = s2 + s3;
        Integer num1 = new Integer(10);
        Integer num2 = new Integer(10);
        System.out.println(s1 == s4);
        System.out.println(s1 == s5);
        System.out.println(s1 == s6);
        System.out.println(s1 == s7);
        System.out.println(s5 == s6);
        System.out.println("===================");
        System.out.println(s1.equals(s4));
        System.out.println(s1.equals(s5));
        System.out.println(s1.equals(s6));
        System.out.println(s1.equals(s7));
        System.out.println(s5.equals(s6));
        System.out.println("===================");
        System.out.println(num1 == num2);
        System.out.println(num1 == 10);
        System.out.println(num1 == new Integer(10));
        System.out.println(num1.equals(new Integer(10)));
    }
}

The operation results are as follows

Topics: Java