Easy Tutorial
❮ Java Arraylist Contains Env Version ❯

Java compareTo() Method

Java String Class


The compareTo() method is used for two types of comparisons:

Syntax

int compareTo(Object o)

or

int compareTo(String anotherString)

Parameters

Return Value

The return value is an integer. It compares the characters based on their ASCII values. If the first characters of both strings are not equal, the comparison ends and returns the difference in their lengths. If the first characters are equal, it proceeds to compare the second characters, and so on, until one of the strings ends.

Note:

If the first characters of both strings are not equal, the comparison ends and returns the difference in their ASCII values.

If the first characters are equal, it proceeds to compare the second characters, and so on, until they are not equal, and returns the difference in their ASCII values.

If both strings are of different lengths but have identical characters up to the length of the shorter string, it returns the difference in their lengths.

Example

public class Test {

    public static void main(String args[]) {
        String str1 = "Strings";
        String str2 = "Strings";
        String str3 = "Strings123";

        int result = str1.compareTo(str2);
        System.out.println(result);

        result = str2.compareTo(str3);
        System.out.println(result);

        result = str3.compareTo(str1);
        System.out.println(result);
    }
}

The output of the above program is:

0
-3
3

Java String Class

❮ Java Arraylist Contains Env Version ❯