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中比较这些字符串,我们需要使用字符串的 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
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战