Compare two Strings lexicographically in Java programming

Java 8Object Oriented ProgrammingProgramming

We can compare two strings lexicographically using following ways in Java.

  • Using String.compareTo(String) method. It compares in case sensitive manner.

  • Using String.compareToIgnoreCase(String) method. It compares in case insensitive manner.

  • Using String.compareTo(Object) method. It compares in case sensitive manner.

These methods returns the ascii difference of first odd characters of compared strings.

Example

 Live Demo

public class Tester {
   public static void main(String args[]) {
      String str = "Hello World";
      String anotherString = "hello world";
      Object objStr = str;
      System.out.println( str.compareTo(anotherString) );
      System.out.println( str.compareToIgnoreCase(anotherString) );
      System.out.println( str.compareTo(objStr.toString()));
   }
}

Output

-32
0
0
raja
Published on 01-Nov-2018 11:49:45
Advertisements