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

To understand this example, you should have the knowledge of the following Java programming topics:


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.

Did you find this article helpful?

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community