Compare two Strings in Java


Compare two strings using compareTo() method in Java. The syntax is as follows −

int compareTo(Object o)

Here, o is the object to be compared.

The return value is 0 if the argument is a string lexicographically equal to this string; a value less than 0 if the argument is a string lexicographically greater than this string; and a value greater than 0 if the argument is a string lexicographically less than this string.

Example

Let us now see an example −

 Live Demo

public class Demo {
   public static void main(String args[]) {
      String str1 = "Strings are immutable";
      String str2 = new String("Strings are immutable");
      String str3 = new String("Integers are not immutable");
      int result = str1.compareTo( str2 );
      System.out.println(result);
      result = str2.compareTo( str3 );
      System.out.println(result);
   }
}

Output

0
10

Let us see another example wherein we are comparing two strings lexicographically, ignoring case differences using compareToIgnoreCase(). This method returns a negative integer, zero, or a positive integer as the specified String is greater than, equal to, or less than this String, ignoring case considerations.

The syntax is as follows −

int compareToIgnoreCase(String str)

Here, str is the string to be compared.

Example

Let us now see an example to compare strings, ignoring case −

 Live Demo

public class Demo {
   public static void main(String args[]) {
      String str1 = "Strings are immutable";
      String str2 = "Strings are immutable";
      String str3 = "Integers are not immutable";
      int result = str1.compareToIgnoreCase( str2 );
      System.out.println(result);
      result = str2.compareToIgnoreCase( str3 );
      System.out.println(result);
      result = str3.compareToIgnoreCase( str1 );
      System.out.println(result);
   }
}

Output

0
10
-10

Updated on: 26-Sep-2019

263 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements