String Comparison In Java
In Java programming language, we can compare two string objects in 3 different ways. That is:
- By Using == operator
- By using equals() method
- By Using compareTo() method
By Using == operator
If you want to compare the reference of the string objects but not the string object content, then, in that case, you can use the == operator. After comparing if both the operands have the same reference, then, in that case, it will return true; otherwise, it will return false.
By equals() method
If you want to compare two string object’s contents, then you can use the equals() method. equals() is an object class method. Still, string class overrides the equals() method and provide below format of equals() methods
- public boolean equals(Object obj): Compares the string with the specified object. Returns true if the actual content is equal, otherwise returns false.
- Public Boolean equalsIgnoreCase(String str): Compares the actual content of the string with the content of the specified string. Returns true if two string’s content is equal, ignoring case, otherwise returns false.
compareTo() method compares the two strings lexicographically, i.e. character by character. The string class provides the following formats of the compareTo() method.
- public int compareTo(String str)
- public int compareToIgnoreCase(String str)
It returns 0 if the argument string is equal to this string, less than 0 if this string is lexicographically less than the string argument and greater than 0 if this string is lexicographically greater than the string argument.