在 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. 我们简单地使用等于运算符 (==) 来比较两个字符串,它将值 BoldBold 进行比较并打印 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

在上面的程序中,我们有两个名为的字符串 stylestyle2 两者都包含同一个词 Bold

但是,我们使用了 String 构造函数来创建字符串。要在 Java 中比较这些字符串,我们需要使用 equals() 字符串的方法。

你不应该使用 == 来比较这些字符串,因为它们比较的是字符串的引用,即它们是否是同一个对象。

而, 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