Java String Compareto Method
Java String Compareto Method
The Java String compareTo() method is used for comparing two strings
lexicographically. Each character of both the strings is converted into a Unicode
value for comparison. If both the strings are equal then this method returns 0 else
it returns positive or negative value. The result is positive if the first string is
lexicographically greater than the second string else the result would be
negative.
For example:
System.out.println(str1.compareTo(str2));
System.out.println(str2.compareTo(str3));
}
}
Output:
Is Java String compareTo() method case sensitive?
In this example, we will compare two strings using compareTo() method. Both
the strings are same, however one of the string is in uppercase and the other
string is in lowercase.
System.out.println(str1.compareTo(str2));
}
}
Output:
As you can see that the output is not zero, which means that compareTo()
method is case sensitive. However we do have a case insensitive compare
method in string class, which is compareToIgnoreCase(), this method ignores the
case while comparing two strings.