What does "compare two strings lexicographically" mean?
We can compare String in Java on the basis of content and reference. It is used in authentication (by equals() method), sorting (by compareTo() method), reference matching (by == operator) etc. There are three ways to compare String in Java: By Using equals() Method.
Java String compareTo() Method The compareTo() method compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The method returns 0 if the string is equal to the other string.
The right way of comparing String in Java is to either use equals(), equalsIgnoreCase(), or compareTo() method. You should use equals() method to check if two String contains exactly same characters in same order. It returns true if two String are equal or false if unequal.
== operator compares the reference of an object in Java. You can use string's equals method .
Leading from answers from @Bozho and @aioobe, lexicographic comparisons are similar to the ordering that one might find in a dictionary.
The Java String class provides the .compareTo ()
method in order to lexicographically compare Strings. It is used like this "apple".compareTo ("banana")
.
The return of this method is an int
which can be interpreted as follows:
compareTo
method is lexicographically first.More specifically, the method provides the first non-zero difference in ASCII values.
Thus "computer".compareTo ("comparison")
will return a value of (int) 'u' - (int) 'a'
(20). Since this is a positive result, the parameter ("comparison"
) is lexicographically first.
There is also a variant .compareToIgnoreCase ()
which will return 0
for "a".compareToIgnoreCase ("A");
for example.
The wording "comparison" is mildly misleading. You are not comparing for strict equality but for which string comes first in the dictionary (lexicon).
This is the feature that allows collections of strings to be sortable.
Note that this is very dependent on the active locale. For instance, here in Denmark we have a character "å" which used to be spelled as "aa" and is very distinct from two single a's (EDIT: If pronounced as "å"!). Hence Danish sorting rules treat two consequtive a's identically to an "å", which means that it goes after z. This also means that Danish dictionaries are sorted differently than English or Swedish ones.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With