Java 程式比較字串以判斷相等性


在 Java 中要比較字串是否相等,請使用 equals() 方法。讓我們看幾個示例,其中我們檢查了相同和不同的字串值。

示例

 線上示例

public class Demo {
    public static void main(String[] args) {
       String one = "x";
       String two = "x";
       if(one.equals(two)) {
          System.out.println("String one is equal to two i.e. one==two");
       }else{
          System.out.println("String one is not equal to String two i.e. one!=two");
       }
    }
}

輸出

String one is equal to two i.e. one==two

讓我們看另一個示例。

示例

 線上示例

public class Demo {
    public static void main(String[] args) {
       String one = "x";
       String two = "y";
       if(one.equals(two)) {
          System.out.println("String one is equal to two i.e. one==two");
       }else{
          System.out.println("String one is not equal to String two i.e. one!=two");
       }
    }
}

輸出

String one is not equal to String two i.e. one!=two

更新日期:2020 年 6 月 26 日

192 次瀏覽

動你的職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.