Java.lang Package Classes

Java String - compareTo() Method



The java.lang.String.compareTo() method is used to compare two strings lexicographically. The comparison is based on the Unicode value of each character in the strings.

Syntax

public int compareTo(String anotherString)

Parameters

anotherString 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.

import java.lang.*;

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.lang - String