Java如何检查字符串是否相等?
为了比较字符串的内容相等性,我们必须使用String.equals()方法。此方法确保将比较两个字符串的内容而不是两个字符串的对象引用。true如果两个比较字符串的内容相同,则返回此方法。
永远不要使用==运算符来比较字符串的内容。该==对象引用相等运算符检查,它返回true只有当两个对象指向相同的参考。false如果对象没有指向相同的引用,则此运算符返回。
package org.nhooo.example.lang;
public class StringEquals {
public static void main(String[] args) {
String s1 = "Hello World";
String s2 = new String("Hello World");
//很好!
if (s1.equals(s2)) {
System.out.println("1. Both strings are equals.");
} else {
System.out.println("1. Both strings are not equals.");
}
//这不好!
if (s1 == s2) {
System.out.println("2. Both strings are equals.");
} else {
System.out.println("2. Both strings are not equals.");
}
}
}在上面的示例中,我们故意s2使用new运算符创建字符串的实例,以确保我们具有不同的对象引用。当您运行该程序时,它将得到以下结果:
1. Both strings are equals. 2. Both strings are not equals.
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短