Java Tutorial Java Advanced Java Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

Java - String compareTo() Method



The Java string 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

5