An example of Java's equals and = = comparison

  • 2020-04-01 03:13:28
  • OfStack

Here's an example:


package com.amos;

public class EqualTest {
    public static void main(String[] args) {
        int a = 1;
        float b = 1.0f;
        System.out.println(a == b);// true
        String c = new String("hi_amos");
        String d = new String("hi_amos");
        System.out.println(c == d);// false
        System.out.println(c.equals(d));// true
    }
}

There are two main ways to determine whether two variables are equal in Java: one is to use the == operator, and the other is to use the equals method to determine whether they are the same.

1). When using == to judge whether two variables are equal or not, true will be returned if two variables are of basic type variables and both of them are numerical types, and the data types are not strictly the same, as long as the values of two variables are equal.

2). If for two reference type variables, they must point to an object, the == judgment returns true.

When the same new String can be interpreted as above,== returns false and equals returns true.

Equals method for the String class, look at its source code, you can see that equals is only a special case of ==, as shown in the following source code:


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;
    }

The equals method actually calls the == discriminant in the first place, and then determines whether the further value is correct


Related articles: