CoderSathi
  • Tutorial
    • Java Tutorial
    • Swing Tutorial
    • JDBC Tutorial
    • Java String Tutorial
    • Servlet and JSP Tutorial
  • Mongo DB
  • AWS
  • DevOps
  • Linux
  • Git
Home > String > Java String Comparison: equals(), ==, and compareTo() Explained

Java String Tutorial

  • Introduction to String
  • String Immutability
  • Common Methods
  • String Comparison
  • Formatting in String
  • Performance Optimization
  • String Manipulation
  • Java Regex Example
  • Special Characters in String
  • String Security
  • Java 8+ String Enhancements
  • Internationalization
  • Advanced Java String Techniques
  • Java String Best Practices

Java String Comparison: equals(), ==, and compareTo() Explained

Learn the concepts, implementation details, and practical steps with a clean developer-focused walkthrough.

Yuba Raj Kalathoki
By Yuba Raj Kalathoki
Last updated: July 1, 2026 · 3 min read · 0 Comments
Share: in X

Table of Contents

  • Why String Comparison is Tricky in Java
    • 1. == Operator: Reference Comparison
    • 2. equals(): Value Comparison
    • 3. equalsIgnoreCase(): Case-Insensitive Check
    • 4. compareTo(): Lexicographical Order
  • Common Mistakes
    • ❌ Using == for Value Checks
    • ❌ NullPointerException with equals()
  • Best Practices
  • FAQ
    • Why does == sometimes work for Strings?
    • What’s the difference between compareTo() and equals()?

Why String Comparison is Tricky in Java

Strings are objects, not primitives. Comparing them incorrectly can lead to logical bugs. Let’s break down the right (and wrong) ways to compare Strings.

1. == Operator: Reference Comparison

The == operator checks if two String variables point to the same memory object, NOT whether their values are equal.

String s1 = "Java";  
String s2 = "Java";  
String s3 = new String("Java");  

System.out.println(s1 == s2);  // true (same object in String Pool)  
System.out.println(s1 == s3);  // false (different objects)  

When to Use ==:

  • Rarely! Only if you intentionally want to check memory equality (e.g., interning).

2. equals(): Value Comparison

The equals() method checks if two Strings have the same sequence of characters.

String s4 = new String("Hello");  
String s5 = new String("Hello");  

System.out.println(s4.equals(s5));  // true (values match)  
System.out.println(s4.equals(null));  // false (avoids NullPointerException)  

Best Practice:

  • Always use equals() for content checks.
  • Handle null safely:
// Avoid:  
if (str.equals("text")) { ... }  // Throws NPE if str is null  

// Safer:  
if ("text".equals(str)) { ... }  // Handles null gracefully  

3. equalsIgnoreCase(): Case-Insensitive Check

Compare Strings while ignoring case differences:

String lang1 = "JAVA";  
String lang2 = "java";  

System.out.println(lang1.equalsIgnoreCase(lang2));  // true  

Use Case: Validating user input (e.g., “YES” vs “yes”).

4. compareTo(): Lexicographical Order

The compareTo() method checks alphabetical order and returns:

  • 0 if equal.
  • Negative if the string comes before the argument.
  • Positive if it comes after.
String a = "apple";  
String b = "banana";  

System.out.println(a.compareTo(b));  // -1 ("apple" < "banana")  
System.out.println(b.compareTo(a));  // 1 ("banana" > "apple")  

Case-Insensitive Version:

System.out.println("A".compareToIgnoreCase("a"));  // 0  

Common Mistakes

❌ Using == for Value Checks

String input = new String("admin");  
if (input == "admin") { ... }  // False! Uses different objects.  

❌ NullPointerException with equals()

String password = null;  
if (password.equals("secret")) { ... }  // Throws NPE  

Best Practices

  1. Always Prefer equals() Over == for content checks.
  2. Handle Nulls Safely: Use Objects.equals() (Java 7+) for null-safe comparisons:
import java.util.Objects;  
System.out.println(Objects.equals(str1, str2));  
  1. Use compareTo() for Sorting: Essential for ordering in lists or trees.

FAQ

Why does == sometimes work for Strings?

When both Strings are literals, they share the same pooled object. Never rely on this for logic!

What’s the difference between compareTo() and equals()?

equals() checks equality, while compareTo() determines alphabetical order.

Up Next: String Formatting: Learn to format Strings with String.format(), printf(), and more.

Related Posts:

  • Control Statements in Java
  • == vs .equals() in Java: What’s the Difference?
  • Default Variable Initialization in Java
  • Java String Best Practices and Common Pitfalls
  • Pass by Value vs. Pass by Reference in Java
  • Java String: Introduction to String in Java
Tags:javalanguage-fundamentalsString
Was this article helpful?
← Previous ArticleJava String Methods: Essential Operations You Must Know
Next Article →Java String Formatting Guide: printf(), String.format(), and More

Leave a Comment Cancel reply

You must be logged in to post a comment.

Recent Posts

  • How to implement Passwordless Authentication in Spring Boot: A Step-by-Step Guide
  • How to Use AWS CloudFront Signed URLs in Spring Boot?
  • How to Fix SSH Agent Forwarding on macOS: The Ultimate Guide for Developers
  • How to Read AWS Secrets Manager in Spring Boot (Step-by-Step)
  • How to Fix “Public Key Retrieval is not allowed” MySQL JDBC Error
CoderSathi

Your go-to resource for Java, Spring Boot, Microservices, AWS, and modern development tutorials.

Linkedin

Quick Links

  • About
  • Contact

Popular Topics

  • Java
  • Spring Boot
  • AWS
  • DevOps
  • MongoDB
  • Linux
  • Git
  • How to
© 2026 CoderSathi. All rights reserved. Privacy Policy · Sitemap