Let’s take a look at the example first:
The code copy is as follows:
package com.amos;
/**
* @ClassName: EqualTest
* @Description: Comparison of equal and == in Java
* @author: amosli
*/
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 judge 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 the two are the same.
1). When using == to determine whether two variables are equal, if the two variables are basic type variables and are both numeric types, the data types are not required to be strictly the same. As long as the values of the two variables are equal, true will be returned. .
2). If for two reference type variables, they must point to an object, then == judgment will return true.== cannot be used to compare two objects with no parent-child relationship on the type.
As mentioned above, when the same new String is explained, == determines whether the same returns false, while equals returns true.
The String class targeted by the equals method, check its source code and you can find that equals can only be regarded as a special case of ==. As shown in the following source code:
The code copy is 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;
}
The equals method actually calls the == discriminant formula from the beginning, and then determines whether its further value is correct.