Google News
logo
Java Program to Compare Strings
In the following example of Java program to compare strings :
Program :
public class StringCompare {
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = "Hello";
        String str3 = "hello";
        String str4 = "Goodbye";
        
        System.out.println("Comparing str1 and str2: " + str1.equals(str2));
        System.out.println("Comparing str1 and str3: " + str1.equals(str3));
        System.out.println("Comparing str1 and str4: " + str1.equals(str4));
        
        System.out.println("Comparing str1 and str2 (ignore case): " + str1.equalsIgnoreCase(str2));
        System.out.println("Comparing str1 and str3 (ignore case): " + str1.equalsIgnoreCase(str3));
        System.out.println("Comparing str1 and str4 (ignore case): " + str1.equalsIgnoreCase(str4));
        
        System.out.println("Comparing str1 and str2 (using compareTo): " + str1.compareTo(str2));
        System.out.println("Comparing str1 and str3 (using compareTo): " + str1.compareTo(str3));
        System.out.println("Comparing str1 and str4 (using compareTo): " + str1.compareTo(str4));
    }
}
Output :
Comparing str1 and str2: trueComparing str1 and str3: false
Comparing str1 and str4: false
Comparing str1 and str2 (ignore case): true
Comparing str1 and str3 (ignore case): true
Comparing str1 and str4 (ignore case): false
Comparing str1 and str2 (using compareTo): 0
Comparing str1 and str3 (using compareTo): -32
Comparing str1 and str4 (using compareTo): 1
In this program, we define four strings str1, str2, str3, and str4 to compare. We then call various methods to compare these strings.

The equals() method is used to check if two strings are equal. It returns true if the two strings have the same characters in the same order, and false otherwise.

The equalsIgnoreCase() method is similar to equals(), but it ignores case. It returns true if the two strings have the same characters in any case, and false otherwise.

The compareTo() method is used to compare two strings lexicographically. It returns an integer value that indicates the relationship between the two strings. If the two strings are equal, it returns 0. If the first string is less than the second string, it returns a negative value. If the first string is greater than the second string, it returns a positive value.

Note that the compareTo() method is case-sensitive, so str1.compareTo(str3) returns a negative value. If you want to compare strings without considering case, you can use the compareToIgnoreCase() method instead.