Pin It

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 :



Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot