原文: https://www.programiz.com/java-programming/examples/compare-strings
public class CompareStrings {
public static void main(String[] args) {
String style = "Bold";
String style2 = "Bold";
if(style == style2)
System.out.println("Equal");
else
System.out.println("Not Equal");
}
}
运行该程序时,输出为:
Equal
在上面的程序中,我们有两个字符串style
和style2
。 我们仅使用相等运算符(==
)比较两个字符串,这会将值Bold
与Bold
进行比较,并输出Equal
。
public class CompareStrings {
public static void main(String[] args) {
String style = new String("Bold");
String style2 = new String("Bold");
if(style.equals(style2))
System.out.println("Equal");
else
System.out.println("Not Equal");
}
}
运行该程序时,输出为:
Equal
在上面的程序中,我们有两个字符串style
和style2
都包含相同的全局Bold
。
但是,我们使用了String
构造器来创建字符串。 要在 Java 中比较这些字符串,我们需要使用字符串的equals()
方法。
您不应该使用==
(相等运算符)来比较这些字符串,因为它们会比较字符串的引用,即它们是否是同一对象。
另一方面,equals()
方法比较字符串的值是否相等,而不是对象本身。
如果改为将程序更改为使用等号运算符,则会显示Not Equal
,如下所示。
public class CompareStrings {
public static void main(String[] args) {
String style = new String("Bold");
String style2 = new String("Bold");
if(style == style2)
System.out.println("Equal");
else
System.out.println("Not Equal");
}
}
运行该程序时,输出为:
Not Equal
这是在 Java 中可能进行的字符串比较。
public class CompareStrings {
public static void main(String[] args) {
String style = new String("Bold");
String style2 = new String("Bold");
boolean result = style.equals("Bold"); // true
System.out.println(result);
result = style2 == "Bold"; // false
System.out.println(result);
result = style == style2; // false
System.out.println(result);
result = "Bold" == "Bold"; // true
System.out.println(result);
}
}
运行该程序时,输出为:
true
false
false
true