示例 1:比较两个字符串
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。
示例 2:使用 equals() 比较两个字符串
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中比较这些字符串,我们需要使用字符串的 equal() 方法。
你不应该使用 ==
(相等运算符) 来比较这些字符串,因为它们比较的是字符串的引用,即它们是否是同一个对象。
另一方面,equals()
方法比较的是字符串的值是否相等,而不是对象本身。
如果你将程序改为使用相等运算符,你将得到 Not Equal,如下面的程序所示。
示例 3:使用 == 比较两个字符串对象(无效)
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
示例 4:比较两个字符串的不同方法
这是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