equals() method:
The equals() method is used to compare a string with the specified object. The equals() method is overridden in the String class to compare whether the contents of two strings are equal.
grammar:
//object:与字符串进行比较的对象
public boolean equals(Object anObject)
return value:
Returns true if the given object is equal to the string; false otherwise.
public class Test {
public static void main(String args[]) {
String Str1 = new String("runoob");
String Str2 = Str1;
String Str3 = new String("runoob");
boolean retVal;
retVal = Str1.equals( Str2 );
System.out.println("返回值 = " + retVal );
retVal = Str1.equals( Str3 );
System.out.println("返回值 = " + retVal );
}
}
//输出
返回值 = true
返回值 = true
Use == and equals() to compare strings:
In String, == compares whether the reference address is the same, and equals() compares whether the content of the string is the same:
String s1 = "Hello"; // String 直接创建
String s2 = "Hello"; // String 直接创建
String s3 = s1; // 相同引用
String s4 = new String("Hello"); // String 对象创建
String s5 = new String("Hello"); // String 对象创建
s1 == s1; // true, 相同引用
s1 == s2; // true, s1 和 s2 都在公共池中,引用相同
s1 == s3; // true, s3 与 s1 引用相同
s1 == s4; // false, 不同引用地址
s4 == s5; // false, 堆中不同引用地址
s1.equals(s3); // true, 相同内容
s1.equals(s4); // true, 相同内容
s4.equals(s5); // true, 相同内容