Difference between == and equals() in comparing Java String objects?

When we use == (shallow comparison), we are actually comparing the two object references to see if they point to the same object. When we use equals(), which is a "deep comparison" that compares the actual string values. 

Equals() method is defined in Object class in Java and used for checking equality of two objects defined by business logic.

“==” or equality operator in Java is a binary operator provided by Java programming language and used to compare primitives and objects. public boolean equals(Object o) is the method provided by the Object class. The default implementation uses == operator to compare two objects. For example: method can be overridden like String class. equals() method is used to compare the values of two objects.


public class StringDemo 
	 public static void main(String[] args) 
	   String S1 = "Hello World";
	   String S2 = new String(S1);
	   String S3 = "Hello World";
	   System.out.println(S1.equals(S2)); //Output: true
	   System.out.println(S1 == S2); // Output: false
	   System.out.println(S1 == S3); // Output true

S1.equals(S2) will return true, because equals compare strings.

S1==S2 will return false, because they do not refer same object. 

S1==S3, S1 and S3 both point to the same object due to internal caching. The references S1 and S3 are interned and points to the same object in the string pool.