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

 


For more of such hot topics read my other posts here :

Visit my new website



Article Written By jontymagicman

I am DInesh Varyani.

Last updated on 26-07-2016 340 0

Please login to comment on this post.
There are no comments yet.
How To Use Java.net.inetaddress Class For Java Networking ?.
How To Implement Comparator Interface In Java With An Example ?