java使用==和equals()判断字符串是否相等

equals()方法:

equals()方法用于将字符串与指定的对象比较。String类中重写了equals()方法用于比较两个字符串的内容是否相等。

语法:

//object:与字符串进行比较的对象
public boolean equals(Object anObject)

返回值:

如果给定对象与字符串相等,则返回true;否则返回false。

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

使用 == 和 equals()比较字符串:

在String中,==比较引用地址是否相同,equals()比较字符串的内容是否相同:

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, 相同内容

猜你喜欢

转载自blog.csdn.net/li_w_ch/article/details/111303454