Home page

Thursday, June 8, 2023

Compare two Strings in JAVA

 public class StringComparisonExample {

    public static void main(String[] args) {

        String str1 = "Hello";

        String str2 = "World";


        // Using equals() method for string comparison

        boolean isEqual1 = str1.equals(str2);

        System.out.println("Using equals() method: " + isEqual1);


        // Using compareTo() method for string comparison

        int comparisonResult = str1.compareTo(str2);

        if (comparisonResult == 0) {

            System.out.println("Using compareTo() method: Strings are equal");

        } else if (comparisonResult < 0) {

            System.out.println("Using compareTo() method: str1 comes before str2");

        } else {

            System.out.println("Using compareTo() method: str1 comes after str2");

        }

    }

}

In this example, we have two strings str1 and str2 that we want to compare.

1. We use the equals() method to compare the two strings. The equals() method checks if the content of str1 is equal to the content of str2 and returns a boolean value indicating the result. If the strings are equal, isEqual1 will be true; otherwise, it will be false.

2. We use the compareTo() method to compare the two strings. The compareTo() method compares the strings lexicographically. It returns an integer value that represents the comparison result. If the result is 0, it means the strings are equal. If the result is negative, it means str1 comes before str2 in lexicographic order. If the result is positive, it means str1 comes after str2 in lexicographic order. We then use conditional statements to print the appropriate message based on the comparison result.

Output:
Using equals() method: false
Using compareTo() method: str1 comes before str2

No comments:

Post a Comment