How can we compare strings in Java using compareTo?

In Java, you can use the compareTo method to compare strings.

public class CompareStrings {
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = "World";
        
        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 is equal to str2");
        }
    }
}

In the above code, we compare str1 and str2 using the compareTo method. If the return value is negative, it means str1 is smaller than str2; if it is positive, it means str1 is greater than str2; if it is 0, it means str1 is equal to str2.

Please note that the compareTo method is case-sensitive. If you need to perform a case-insensitive comparison, you can use the compareToIgnoreCase method.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds