Skip to main content
Browse topics

String Equals vs == Operator Example in Java

2 min read Updated May 29, 2026
Share

Introduction

Comparing strings is one of the most common tasks in Java, but beginners often confuse the == operator with the equals() method. This program demonstrates both and explains when each is appropriate.

Key Difference

Operator / MethodCompares
==Whether two references point to the same object in memory
equals()Whether two strings have the same character sequence
equalsIgnoreCase()Same as equals() but ignores letter case

Example Program

java
public class StringCompareDemo {
    public static void main(String[] args) {
        String a = new String("Java");
        String b = new String("Java");
        String c = "Java";
        String d = "Java";

        System.out.println("a == b        : " + (a == b));
        System.out.println("a.equals(b)   : " + a.equals(b));
        System.out.println("c == d        : " + (c == d));
        System.out.println("c.equals(d)   : " + c.equals(d));

        String s1 = "hello";
        String s2 = "HELLO";
        System.out.println("s1.equals(s2)            : " + s1.equals(s2));
        System.out.println("s1.equalsIgnoreCase(s2)  : " + s1.equalsIgnoreCase(s2));
    }
}

Sample Output

plaintext
a == b        : false
a.equals(b)   : true
c == d        : true
c.equals(d)   : true
s1.equals(s2)            : false
s1.equalsIgnoreCase(s2)  : true

How It Works

  • new String("Java") creates distinct objects on the heap, so a == b is false even though the text matches.
  • String literals "Java" are interned in the string pool; c and d refer to the same pooled object, so c == d is true.
  • For content comparison, always prefer equals() or equalsIgnoreCase().

Best Practices

Common Mistakes

Frequently Asked Questions

Does == compare string characters in Java?
No. == compares object references (memory addresses). Two String variables can point to different objects with the same text, so == may return false even when the content matches.
When should I use equalsIgnoreCase()?
Use equalsIgnoreCase() when comparing user input or case-insensitive identifiers such as command names or email domains.

Related tutorials

Search tutorials