Java String.equals() 與 ==


equals() 方法將此字串與指定物件進行比較。當且僅當引數不為 null 且是一個表示與此物件相同的字元序列的 String 物件時,結果才為 true。

示例

即時演示

public class Sample {
   public static void main(String []args) {
      String s1 = "tutorialspoint";
      String s2 = "tutorialspoint";
      String s3 = new String ("Tutorials Point");
      System.out.println(s1.equals(s2));
      System.out.println(s2.equals(s3));
   }
}

輸出

true
false

您還可以使用 == 運算子比較兩個字串。但是,它比較給定變數的引用,而不是值。

示例

即時演示

public class Sample {
   public static void main(String []args) {
      String s1 = "tutorialspoint";
      String s2 = "tutorialspoint";
      String s3 = new String ("Tutorials Point");
      System.out.println(s1 == s2);
      System.out.println(s2 == s3);
   }
}

輸出

true
false

更新日期:2020 年 2 月 26 日

207 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告