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 次浏览

开启你的 仕途

完成课程认证

开始吧
广告