The difference between == and equals in Java
- 2020-04-01 03:54:23
- OfStack
public class Compare {
public static void main(String[] args) {
String s1 = new String("Hello,World!"); //Create two string-type object references;
String s2 = new String("Hello,World!");
String s3 = s1; //Assign a reference to s1 object to s3
System.out.println("s2==s3 The result of operation is :" + (s2==s3)); //Different addresses
System.out.println("s1==s3 The result of operation is :" + (s1==s3)); //Address is the same
System.out.println("s2.equals(s3) The result of operation is :"+(s2.equals(s3)));//Content is the same
}
}
Result of s2 = = s3 is: false
The result of s1==s3 is :true
The result of s2.equals(s3) is :true
Conclusion:
The equals() method is a method in the String class that compares two object references to each other. And == compares the addresses of two object references. Since s1 and s2 are two different object references in different locations in memory, the String s3 =s1 statement assigns a reference to s1 to s3, so s1 and s3 are equal object references.