📜  Java程序区分字符串== 运算符和equals()方法

📅  最后修改于: 2020-09-26 18:23:00             🧑  作者: Mango

在本教程中,我们将学习区分Java中的字符串 == 运算符和equals()方法

示例1:区分==和equals()的Java程序
class Main {

  public static void main(String[] args) {

    String name1 = new String("Programiz");
    String name2 = new String("Programiz");

    System.out.println("Check if two strings are equal");

    // check if two strings are equal
    // using == operator
    boolean result1 = (name1 == name2);
    System.out.println("Using == operator: " + result1);

    // using equals() method
    boolean result2 = name1.equals(name2);
    System.out.println("Using equals(): " + result2);
  }
}

输出

Check if two strings are equal
Using == operator: false
Using equals(): true

在上面的示例中,我们使用== 运算符和equals()方法检查两个字符串是否相等。这里,

  • ==检查对字符串对象的引用是否相等。在此, name1name2是两个不同的引用。因此,它返回false
  • equals()检查字符串对象的内容是否相等。在这里,对象name1name2的内容都是相同的Programiz 。因此,它返回true

示例2:微分==和equals()
class Main {

  public static void main(String[] args) {

    String name1 = new String("Programiz");
    String name2 = name1;

    System.out.println("Check if two strings are equal");

    // check if two strings are equal
    // using == operator
    boolean result1 = (name1 == name2);
    System.out.println("Using == operator: " + result1);

    // using equals() method
    boolean result2 = name1.equals(name2);
    System.out.println("Using equals(): " + result2);
  }
}

输出

Check if two strings are equal
Using == operator: true
Using equals(): true

在这里, 名称1名称2引用相同的对象。因此, name1 == name2返回true