What are differences between equals and ==

What are differences between equals and == ?

Answer : Difference is == compares just two references for non-primitives – i.e. it will test whether the two operands refer to the same object. It will check if the objects refer to same place on the memory.

On the other hand, equals method could be overridden – so two distinct objects will be equal. Actually equals method compares the contents of two objects, and not their location in memory as == compares. Please see example below:

What are differences between equals and ==

package com.javahonk.equalsTest;

public class EqulasTest {

public static void main(String[] args) {
String J1 ="Java Honk";
String J2 ="Java Honk";
String J3 ="Java Honk";

if (J1 == J2) {
System.out.println("String literals comparison true");
System.out.println("Name: "+J1);
}

if (J2 == J3) {
System.out.println("String literals comparison true");
System.out.println("Name: "+J2); 
}

if (J1 == J3) {
System.out.println("String literals comparison true");
System.out.println("Name: "+J3); 
}

String J4 =new String("Java Honk");
String J5 =new String("Java Honk");

if (J1 == J5) {
System.out.println("String literals comparison true");
System.out.println("Name: "+J1);
}else {
System.out.println("String literals and object "
+ "comparison not true"); 
}

if (J1.equalsIgnoreCase(J5)) {
System.out.println("String literals and object "
+ "comparison equals true");
System.out.println("Name: "+J5);
}

}

}

 

Output:

What are differences between equals and ==

Leave a Reply

Your email address will not be published. Required fields are marked *