Cover Image for String compareTo()
182 views

String compareTo()

The Java compareTo() method is used to compare two strings lexicographically (i.e., based on their alphabetical order). It is often used to determine the relative order of two strings, and it returns an integer that indicates the result of the comparison. The basic syntax of the compareTo() method is as follows:

int result = str1.compareTo(str2);
  • str1 and str2: The two strings you want to compare.

The compareTo() method returns an integer value that has the following meanings:

  • If str1 is lexicographically less than str2, the result is a negative integer (usually less than 0).
  • If str1 is lexicographically greater than str2, the result is a positive integer (usually greater than 0).
  • If str1 and str2 are lexicographically equal, the result is 0.

Here’s an example:

public class CompareToExample {
    public static void main(String[] args) {
        String str1 = "apple";
        String str2 = "banana";

        int result = str1.compareTo(str2);

        if (result < 0) {
            System.out.println("str1 is less than str2");
        } else if (result > 0) {
            System.out.println("str1 is greater than str2");
        } else {
            System.out.println("str1 and str2 are equal");
        }
    }
}

In this example, str1 and str2 are compared using the compareTo() method. Since “apple” comes before “banana” in lexicographic order, the result is negative, and the program prints “str1 is less than str2.”

It’s important to note that the compareTo() method is case-sensitive, so uppercase letters come before lowercase letters in lexicographic order. To perform a case-insensitive comparison, you can use the compareToIgnoreCase() method, which ignores the case of characters when comparing strings:

int result = str1.compareToIgnoreCase(str2);

The compareTo() and compareToIgnoreCase() methods are commonly used in sorting and searching algorithms, as well as for ordering and comparing strings in various applications.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS