Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in Java by (7k points)

What does “compare two strings lexicographically” mean?

1 Answer

0 votes
by (13.1k points)

A lexicographic comparison is something similar to the ordering that one might find in a dictionary.

Java String class provides the .compareTo() method in order to lexicographically compare Strings. It is used like this “kiwi”.compareTo(“pineapple”) .

The return of this method is an int which can be interpreted as follows:

  • returns < 0 

then the string is calling the method that lexicographically comes first

  •   returns==0 

then the two strings are lexicographically equivalent

  • returns>0

then the parameter passed to the compareTo method is lexicographically first.

The method provides the first non-zero difference in ASCII values.

There is also a variant .compareToIgnoreCase() which will return 0 for “b”.compareToIgnoreCase(“B”);

Want to learn Java? Check out the Java certification from Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Mar 4, 2021 in Java by rahulnayar01123 (6.1k points)
0 votes
1 answer
0 votes
1 answer
asked Apr 1, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
asked Mar 19, 2021 in Java by Jake (7k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...