Java 程序:比较字符串
要理解这个例子,你需要了解以下 Java 编程 主题的知识:
示例 1:比较两个字符串
public class CompareStrings {
public static void main(String[] args) {
String style = "Bold";
String style2 = "Bold";
if(style == style2)
System.out.println("相等");
else
System.out.println("不相等");
}
}
输出
相等
在上面的程序中,我们有两个字符串 style
和 style2
。我们简单地使用等于运算符(==
)来比较两个字符串,它将值 Bold 与 Bold 比较,然后打印 相等。
示例 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("相等");
else
System.out.println("不相等");
}
}
输出
相等
在上面的程序中,我们有两个名为 style
和 style2
的字符串,都包含相同的单词 Bold。
然而,我们使用了 String
构造函数来创建这些字符串。为了在 Java 中比较这些字符串,我们需要使用字符串的 equals()
方法。
你不应该使用 ==
(等于运算符)来比较这些字符串,因为它们比较的是字符 串的引用,即它们是否是同一个对象。
另一方面,equals()
方法比较的是字符串的值是否相等,而不是对象本身。
如果你将程序改为使用等于运算符,你会得到 不相等,如下面的程序所示。
示例 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("相等");
else
System.out.println("不相等");
}
}
输出
不相等
示例 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