What is Shallow comparison and deep comparison in String comparison

What is Shallow comparison and deep comparison in String comparison

Welcome back, friends. Most of the Java developers knows What is different between “equals” and “==” operator and how it different while comparing two string using “equals” and “==”. 
String name1 = “Suresh”;
String name2 = new String(“Suresh”);
System.out.println(name1 == name2); // false
System.out.println(name1.equals(name2)); // true

In the above program, name1 and name2 are having “Suresh” value. If we use the “==” operator for comparing the two String values, it gives false. Both values are the same but it is giving false. Why? The reason is, “==” equal to operator compares two String value’s memory addresses(reference). According to the above program, name1 and name2 are having two different memory addresses so it is not matching thas the reason it is giving false. This is called Shallow comparison

if we use the equals function, it compares the value of two String variables. Since both variables is having the same value and it returns true. This is called Deep comparison.

What will happen if you just assign like below instead of a new operator.
String name1 = “Suresh”;
String name2 = “Suresh”;
System.out.println(name1 == name2); // true
Now I am using the “==” operator and “equals” function. In this case, both
return “true”. Why? “==” it gives true, because of String caching mechanism. The “==” operator not comparing values, it compares the only address of name1 and name2 variables. The reason it gives true is, whenever we assign a value to a string variable, Java checks that if the value already exists in the String Pool, if exists, it assigns the same memory address to the new variable. So, both variable’s memory addresses are the same hence, it gives true. In our example, name1 is having “Suresh”, Java creates a new memory address for the value “Suresh” and keeps this value in the String Pool area. I am again creating a new variable called name2 and assigning the same value “Suresh”. Java checks in the Pool area, if any variable is having the same value “Suresh”, it returns the address of the variable and assigns it to a newly created variable. so When use name1 == name2 , it return true. Because of these two-variable pointing same memory address.
I hope you understand the concepts

Please follow our ITGARDEN YouTube channel for Billing System Project development work using Spring Boot. The Project source code absolutely free. This project is very good for those who are looking for real-time project experience in Spring Boot. To understand the Billing System Project code, watch all Billing System-related YouTube videos from this link. Click Here
Our YouTube Channel
Please follow me on Medium.com for all billing system related stories and Java-based technical Articles
Note: To find all billing System-related stories find “billing system itgarden” in medium.com

Close Menu