Analyze two strings for equality.
String myStr1 = "Hello"; String myStr2 = "Hello"; System.out.println(myStr1.compareTo(myStr2)); // Returns 0 because they are equal |
The compareTo() method performs a lexicographical comparison of two strings, relying on the Unicode values of their respective characters.
The method yields 0 when the string equals the other string. It returns a value less than 0 if the string is shorter than the other string and a value greater than 0 if the string is longer than the other string.
Tip: Consider employing compareToIgnoreCase()
to compare two strings lexicographically while disregarding differences in case
Tip: Utilize the equals()
method to compare two strings without taking Unicode values into consideration.
one of the next:
public |
public |
Parameter |
Description |
string2 |
A string representing the other string for comparison. |
object |
An object representing another object to compare. |
Returns: |
An integer value: 0 indicates equality between the string and the other string. A value less than 0 indicates the string is lexicographically before the other string. A value greater than 0 indicates the string is lexicographically after the other string (having more characters). |