Java String Compare Using equals() Method

When we are trying to compare the values of two string to be equal or not, better to use equals() method. If you are want to check for equality with case insensitivity, then you can use the equalsIgnoreCase() method.

Below code snippet shows examples of string comparison using equals() and equalsIgnoreCase() method.

Java String Compare Using equals() Method

package net.javaguides.corejava;

public class StringExample {

    public static void main(String[] args) {

        String s1 = "abc";
        String s2 = "abc";
        String s3 = new String("ABC");
        System.out.println(s1.equals(s2)); // true
        System.out.println(s1.equals(s3)); // false
        System.out.println(s1.equalsIgnoreCase(s3)); // true
    }
}
Output:
true
false
true
Here is one more example to compare two strings in Java:
// Demonstrate equals() and equalsIgnoreCase().
class equalsDemo {
    public static void main(String args[]) {
        String s1 = "Hello";
        String s2 = "Hello";
        String s3 = "Good-bye";
        String s4 = "HELLO";
        System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
        System.out.println(s1 + " equals " + s3 + " -> " + s1.equals(s3));
        System.out.println(s1 + " equals " + s4 + " -> " + s1.equals(s4));
        System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " + s1.equalsIgnoreCase(s4));
    }
}
The output from the program is shown here:
Hello equals Hello -> true
Hello equals Good-bye -> false
Hello equals HELLO -> false
Hello equalsIgnoreCase HELLO -> true

Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course