There are multiple way to compare two stings alphabetically in Java e.g. == operator, equals() method or compareTo() method,
but which one is the best way to check if two strings are equal or not?
Programmers often confused
between == operator and equals() method, and think that comparing strings
using == operator should be faster than equals() method,
and end up using that. Though they are not completely wrong, they often missed
point that == operator is designed to compare object
equality, not String equality, which is actually defined in equals()method and compare Strings alphabetically. When you compare two strings
using == operator, it may or may not return true,
especially if you are expecting result based on contents. It will only return true if both
reference variables are pointing to same object, like in case of interned
string or String literals. Otherwise it will return false, even if
content of String remain same. It's one of the coding best practice in Java to use equals() method to
check String equality, i.e. to check if two String variable contains
same values or not. This method also come with another flavor called equalsIgnoreCase(), which
perform case insensitive equality check and should be used to perform case insensitive equality check.