Core java 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 new operator.
String name1 = “Suresh”;
String name2 = “Suresh”;
For further reading please click the below link