Java教程

Java 比较字符串的程序

比较字符串的 Java 程序

在本程序中,您将学习在 Java 中比较两个字符串。
要理解此示例,您应该了解以下Java 编程主题:
Java 字符串 Java 运算符

示例 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
在上面的程序中,我们有两个字符串 stylestyle2。我们简单地使用等于运算符( ==) 来比较两个字符串,它将值 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("Equal");
        else
            System.out.println("Not Equal");
    }
}
输出
Equal
在上面的程序中,我们有两个名为 stylestyle2 的字符串,它们都包含相同的世界 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("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
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4