Java | Shallow and Deep comparison of objects

Author - Webner

There are two types of object comparison in java – shallow and deep.

when you use ‘==’ operator, you are comparing the references for equality. It means you are comparing memory addresses of the objects. It is called shallow comparison.

When you use .equals() you are comparing the object values themselves for equality. It means you are checking ‘do both objects have same value for corresponding instance variables or not ‘.

Let’s have an example to understand it better:

String person1=”James”; // memory address 500
String person2=”James”; //memory address 500 as the value is same

// Shallow comparison
if(person1== person2){
// It will return true, because it is comparing the memory addresses which are same for both the objects
System.out.println(“Success”);
}


// Deep comparison
if(person1.equals(person2)){

//It will return true, because it is comparing the object values which are again same for both
System.out.println(“Success”);
}

Now we make some changes:

String person2 = new String(“James”); //James now has a new memory address for eg: 2545

if(person1== person2){
// It will return false because it is comparing the memory addresses which are different for both
System.out.println(“Failed”);
}

if(person1 .equals(person2)){
//It will return true because it is comparing the object values which are still the same
System.out.println(“Success”);
}

Webner Solutions is a Software Development company focused on developing CRM apps (Salesforce, Zoho), LMS Apps (Moodle/Totara), Websites and Mobile apps. If you need Web development or any other software development assistance please contact us at webdevelopment@webners.com

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

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