![]() |
VOOZH | about |
String in Java are immutable sequences of characters. Comparing strings is the most common task in different scenarios such as input validation or searching algorithms. In this article, we will learn multiple ways to compare two strings in Java with simple examples.
Example:
To compare two strings in Java, the most common method is equals(). This method compares the content of two strings for equality.
false true
Explanation: In the above example, the equals() method checks the content of s1 and s2. Since they differ, it returns false.It returns true for s1 and s3 because they have identical content.
Table of Content
We can define our own function to compare strings lexicographically. Define a function to compare values with the following conditions :
Example:
6
Explanation: In the above example, we get the output as 6, because the compareTo() method compares strings lexicographically, finding the difference between the first mismatched characters 'J' (Unicode 74) and 'D' (Unicode 68), resulting in 74 - 68 = 6.
The String.equalsIgnoreCase() method compares two strings irrespective of the case (lower or upper) of the string. This method returns true if the argument is not null and the contents of both the Strings are same ignoring case, else false.
Example:
true
Explanation: The equalsIgnoreCase() method treats "Java" and "JAVA" as equal because it ignores case sensitivity.
The Object.equals(Object a, Object b) method returns true if the arguments are equal to each other and false otherwise. Consequently, if both arguments are null, true is returned and if exactly one argument is null, false is returned. Otherwise, equality is determined by using the equals() method of the first argument.
Example:
false true
Note:Objects.equals() avoids NullPointerException by handling null values.
The String.compareTo() method compares strings lexicographically. It compares and returns the values as follows:
Example: