Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

What is difference between equals() method and == operator in Java ?

What is difference between equals() method and == operator in Java ? .
Equals( ) method and == has very vital role to play when comparing two objects of any kind. Both of the equals( ) method and == operator returns true when two objects reference compared with each other points to same objects. While the comparisons change when we override equals method. String class has overridden this method , thats why they show different behavior as demonstrated below.


Program to demonstrate the difference between equals() method and == operator in Java

package com.hubberspot.operators.example;

public class EqualityTest {
  public static void main(String[] args) {
    String string1 = new String("Test");
    String string2 = new String("Test");
    
    String string3 = new String("New Test");
    String string4 = new String("Old Test");
    
    System.out.println("string1 == string2 : "
       + (string1 == string2));
    System.out.println("string1 != string2 : "
       + (string1 != string2));

    System.out.println("string3 == string4 : " 
       + (string3 == string4));
    System.out.println("string3 != string4 : "
       + (string3 != string4));
    
    System.out.println("string1.equals(string2) : "
       +string1.equals(string2));
    
    System.out.println("string3.equals(string4) : "
       +string3.equals(string4));
  }
}

Output of the program :



 
© 2021 Learn Java by Examples Template by Hubberspot