Comparing Strings

equals vs ==

== checks whether two references point to the same object. equals() checks whether the text is the same. Always use equals() to compare String content.

Example

public class Main {
    public static void main(String[] args) {
        String a = "java";
        String b = "java";               // same literal -> same pooled object
        String c = new String("java");   // new object on the heap

        System.out.println(a == b);        // true (same object from the String pool)
        System.out.println(a == c);        // false (different objects)
        System.out.println(a.equals(c));   // true (same text)
        System.out.println("JAVA".equalsIgnoreCase(a));
    }
}

Output

true
false
true
true

compareTo

Example

compareTo() compares alphabetically (dictionary order). It returns a negative number, zero or a positive number.

public class Main {
    public static void main(String[] args) {
        System.out.println("apple".compareTo("banana"));  // negative: apple comes first
        System.out.println("mango".compareTo("mango"));   // 0: equal
        System.out.println("zebra".compareTo("lion"));    // positive: zebra comes later
        System.out.println("Apple".compareToIgnoreCase("apple"));
    }
}

Output

-1
0
14
0

Tip: To avoid a NullPointerException when a value may be null, put the literal first: "admin".equals(role) instead of role.equals("admin").