HOWTO · Java

Java 中的 if 語句比較字串

通過 Java 中的 if 語句比較字串。

本頁內容

在本指南中,我們將討論 Java 中的 if 語句字串比較。比較兩個字串通常有三種方法。你需要了解這些操作的基礎知識並找出你要比較的內容(內容、引用或字串差異)。讓我們更深入地瞭解一下。

使用 == 運算子將字串與 Java if 語句進行比較

當我們使用 == 運算子通過 if 語句比較兩個字串時,我們比較這些字串的引用編號,但你會注意到它與比較內容的工作方式相同。如果有兩個內容相同的字串,它會將它們顯示為相等。為什麼?因為 Java 的編譯器已經足夠成熟,可以將兩個內容相同的字串儲存在同一個記憶體中。

使用 equal() 函式將字串與 Java if 語句進行比較

通過 equal() 函式,我們可以比較兩個字串的內容。它將檢視內容是否相似。它區分大小寫,但你也可以通過使用 equalsIgnoreCase() 函式來忽略區分大小寫。

使用 compareTo() 函式將字串與 Java if 語句進行比較

在這個函式中,我們得到了兩個字串之間的差異。我們根據每個字元的 Unicode 值按字典順​​序比較它們。如果兩個字串相等,你將獲得 0 值,如果字串小於另一個字串,你將獲得小於 0 值,反之亦然。

看看下面的不言自明的程式碼。

public class Main {
  public static void main(String[] args) {
    String str1 = "jeff";
    String str2 = "jeff";
    String str3 = new String("jeff"); // to declare
    String str10 = new String("jeff");
    System.out.println("-----------------Using == Operator ----------------");
    // using == opreater use for Refrence Comapring instead of content comparison.
    if (str1
        == str2) { // equal and if Conditon True because both have same Refrence Memory address.
      System.out.println("Str1 And Str2 Equal");
    }
    if (str1
        == str3) { // Not Equal If Condition False Because == opreater compares objects refrence.
      System.out.println("Str1 and Str3 are equals");
    }
    if (str10
        == str3) { // Not Equal If Condition False Because == opreater compares objects refrence.
      System.out.println("Str10 and Str3 are equals");
    }

    System.out.println("-----------------Using .equal Method----------------");
    // Using .equals Method. for String Content Comparison.

    if (str1.equals(str2)) { // equal and if Conditon True because both have same string
      System.out.println("Str1 And Str2 Equal");
    }
    if (str1.equals(str3)) { // Equal If Condition true String have same Content.
      System.out.println("Str1 and Str3 are equals");
    }
    // compare two strings diffrence
    System.out.println("-----------------Using Compare Method----------------");
    // first string.toCompare(String2)

    System.out.println(str1.compareTo(str2));
  }
}

輸出:

Output:
-----------------Using == Operator ----------------
Str1 And Str2 Equal
-----------------Using .equal Method----------------
Str1 And Str2 Equal
Str1 and Str3 are equals
-----------------Using Compare Method----------------
0