Comparing two Strings lexicographically in Java

Java Programming Java8Object Oriented Programming

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

  • Using String.compareTo(String) method. It compares in a 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 return 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 23-Jul-2018 07:08:37
Advertisements