Java Program to Differentiate String == operator and equals() method

In this tutorial, we will learn to differentiate the string == operator and equals() method in Java

Example 1: Java program to differentiate == and equals()

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);
  }
}

Output

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

In the above example, we have used the == operator and equals() method to check if two strings are equal. Here,

  • == checks if the reference to string objects are equal or not. Here, name1 and name2 are two different references. Hence, it returns false.
  • equals() checks if the content of the string object are equal. Here, the content of both the objects name1 and name2 is the same Programiz. Hence, it returns true.

Example 2: Differentiate == and 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);
  }
}

Output

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

Here, name1 and name2 both are refering to the same object. Hence, name1 == name2 returns true.

Leave a Reply