The relational operators cannot be used to compare the strings. On other hand, method like compareTo() and equals() should be used in string comparison.
Let us write a program to compare two strings using ‘==’ and see result
When an object is created by JVM, it returns the memory address of the object as a hexadecimal number, which is called object reference.
In fact that both string are same. We are getting wrong output. In first string , when JVM creates an object with a reference number and when JVM creates an another object with new operator it creates a another reference number. So the statement (s1==s2) will compares only reference number and both reference number are not same and hence output will be “Not same”.
Actually, to compare the contents of string object we should use ‘equals()’ method.
What is difference between == and equals() while comparing string? Which one is reliable?
== operator compares the reference of the string objects. equals() method compares the content of the object. While computing the strings equals() method should be used as it yield the correct result.