Java 程式用來區分字串 == 運算子和 equals() 方法


在本文中,我們將瞭解如何在 Java 中區分 == 運算子和 equals() 方法。==(等於)運算子檢查兩個運算元的值是否相等,如果相等,則條件變為真。

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

以下是相同的演示 −

假設我們的輸入是

The first string : abcde
The second string: 12345

期望的輸出是

Using == operator to compare the two strings: false
Using equals() to compare the two strings: false

演算法

Step 1 – START
Step 2 - Declare two strings namely input_string_1, input_string_2 and two boolean values namely result_1, result_2.
Step 3 - Define the values.
Step 4 - Compare the two strings using == operator and assign the result to result_1.
Step 5 - Compare the two strings using equals() function and assign the result to result_2.
Step 5 - Display the result
Step 6 - Stop

示例 1

這裡,我們在“main”函式下將所有操作繫結在一起。

public class compare {
   public static void main(String[] args) {
      String input_string_1 = new String("abcde");
      System.out.println("The first string is defined as: " +input_string_1);
      String input_string_2 = new String("12345");
      System.out.println("The second string is defined as: " +input_string_2);
      boolean result_1 = (input_string_1 == input_string_2);
      System.out.println("\nUsing == operator to compare the two strings: " + result_1);
      boolean result_2 = input_string_1.equals(input_string_2);
      System.out.println("Using equals() to compare the two strings: " + result_2);
   }
}

輸出

The first string is defined as: abcde
The second string is defined as: 12345

Using == operator to compare the two strings: false
Using equals() to compare the two strings: false

示例 2

這裡,我們將操作封裝到函式中,展示面向物件程式設計。

public class Demo {
   static void compare(String input_string_1, String input_string_2){
      boolean result_1 = (input_string_1 == input_string_2);
      System.out.println("\nUsing == operator to compare the two strings: " + result_1);
      boolean result_2 = input_string_1.equals(input_string_2);
      System.out.println("Using equals() to compare the two strings: " + result_2);
   }
   public static void main(String[] args) {
      String input_string_1 = new String("abcde");
      System.out.println("The first string is defined as: " +input_string_1);
      String input_string_2 = new String("12345");
      System.out.println("The second string is defined as: " +input_string_2);
      compare(input_string_1, input_string_2);
   }
}

輸出

The first string is defined as: abcde
The second string is defined as: 12345

Using == operator to compare the two strings: false
Using equals() to compare the two strings: false

更新於: 2022-03-29

177 次瀏覽

開啟你的 仕途

完成課程認證

開始吧
廣告
© . All rights reserved.