Java Tutorial Java Advanced Java References

Java String - compareTo() Method



The Java compareTo() method is used to compare two strings lexicographically.

Syntax

public int compareTo(String str)

Parameters

str specify the string to be compared.

Return Value

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

Exception

NA.

Example:

In the example below, compareTo() method is used to compare strings lexicographically.

public class MyClass {
  public static void main(String[] args) {
    String str1 = "Hello World";
    String str2 = "Hello World";
    String str3 = "Learn Java.";

    //comparing str1 and str2
    System.out.println(str1.compareTo(str2));

    //comparing str1 and str3
    System.out.println(str1.compareTo(str3));
  }
}

The output of the above code will be:

0
-4

❮ Java String Methods