CoderSathi
  • Tutorial
    • Java Tutorial
    • Swing Tutorial
    • JDBC Tutorial
    • Java String Tutorial
    • Servlet and JSP Tutorial
  • Mongo DB
  • AWS
  • DevOps
  • Linux
  • Git
Home > Java > == vs .equals() in Java: What’s the Difference?

Java Tutorial

  • Introduction
    • What is Java
    • History Of Java
    • Install Java
    • What is JVM
    • JDK vs JRE vs JVM
    • Java Bytecode
    • OOP vs POP
    • Compile and Run Java
  • Tokens, Expressions and Control Structures
    • Primitive data types
    • Integers
    • Floating Points
    • Characters
    • Booleans
    • User Defined Data Type
    • Declarations
    • Constants
    • Identifiers
    • Literals
    • Type Conversion and Casting
    • Variables
    • Default Variable Initialization
    • Command Line Arguments
    • Arrays of Primitive Types
    • Comment Syntax
    • Garbage Collection
    • Expressions
    • Operators
    • Arithmetic Operator
    • Bitwise and Shift Operator
    • Comparison or Relational Operators
    • Logical Operators
    • Assignment Operators
    • Ternary Operator
    • Increment and Decrement Operator
    • Control Statements
  • OOP Concepts
    • Class and Object
    • Create Class Instance
    • Method
    • Abstraction
    • Encapsulation
    • this keyword
    • Constructor
    • Pass by Value
    • Access Modifier/Control
    • Polymorphism
    • Method Overloading vs Method Overriding
    • Recursion
    • Nested and Inner Class
  • Inheritance and Packaging
    • Inheritance
    • extends Keyword
    • super Keyword
    • Object Class
    • Abstract class
    • Final Class
    • Java Package
    • Interface
  • Handling Error/ Exceptions
    • What is Exception
    • Exception Handling Keywords
    • Common Java Errors
    • User Defined Exception
    • Throwing and re-throwing Exception
    • finally Block
  • Strings
    • Java String Tutorial
  • Threads
    • Introduction
    • Create Thread
    • Thread Lifecycle
    • Thread Priority
    • Thread Synchronization
    • Inner Thread Communication
    • Thread Deadlock
  • IO and Streams
    • java.io Package
    • Files and Directories
    • Byte Stream
    • Character Stream
    • Console Input and Output
    • Serializable and Deserializable
  • Core Packages
    • java.lang Package
    • Math
    • Wrapper Classes
    • java.lang.Number
    • Double
    • Float
    • Integers
    • java.lang.Byte
    • java.lang.Short
    • java.lang.Long
    • java.lang.Character
    • java.lang.Boolean
    • java.util package
    • Vector Class
    • Stack Class
    • Dictionary Class
    • Hashtable
    • Enumeration or Enum
    • Generate Random Number
  • Holding Collection of Data
    • Arrays
    • Map
    • List
    • Set
    • Collection Interface
    • Collections Class
    • ArrayList
    • HashSet
    • TreeSet
    • Comparator
  • Java Bean
    • What is Java Bean
    • Advantages and Disadvantages of Java Bean
    • Java Beans API
    • Introspection
    • Java Bean Properties
    • Bound and Constrained Properties
    • BeanInfo Interface
    • Customizers
    • Java Beans Persistence
    • BeanDescriptor
  • Home

== vs .equals() in Java: What’s the Difference?

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 · 4 min read · 0 Comments
Share: in X

Java developers often mix up the operator == vs .equals() in Java, leading to unexpected bugs. While both are used for comparison, they serve distinct purposes. Understanding the difference between == and .equals() in Java is critical for accurate Java object comparison and avoiding logical errors. Let’s demystify these concepts with clear examples and use cases.

Table of Contents

  • == Operator vs .equals() Method: Core Differences
    • 1. == Operator: Compares References or Primitive Values
    • 2. .equals() Method: Compares Object Content
  • When to Use == vs .equals() in Java
    • Use == For:
    • Use .equals() For:
  • Common Use Cases
    • 1. Java String Comparison
    • 2. Custom Objects
  • Pitfalls to Avoid
    • 1. NullPointerException with .equals()
    • 2. Mixing == and .equals() for Wrapper Classes
  • Key Takeaways
  • Conclusion

== Operator vs .equals() Method: Core Differences

1. == Operator: Compares References or Primitive Values

The Java equality operator (==) checks if two variables point to the same memory location (for objects) or hold the same value (for primitives).

Example with Primitives:

int a = 5;  
int b = 5;  
System.out.println(a == b); // true (values are equal)  

Example with Objects:

String s1 = new String("Hello");  
String s2 = new String("Hello");  
System.out.println(s1 == s2); // false (different memory addresses)  

2. .equals() Method: Compares Object Content

The equals method Java classes (like String, Integer) override this method to compare the actual content of objects, not their memory addresses.

Example:

String s1 = new String("Hello");  
String s2 = new String("Hello");  
System.out.println(s1.equals(s2)); // true (content is identical)  

When to Use == vs .equals() in Java

Use == For:

  • Primitive type comparisons (e.g., int, char).
  • Checking if two object references point to the same instance.

Use .equals() For:

  • Java object comparison (e.g., String, custom classes).
  • Comparing logical equality (e.g., two different Integer objects with the same value).

Common Use Cases

1. Java String Comparison

Strings are a classic example where using == can fail:

String literal1 = "Java";  
String literal2 = "Java";  
String obj1 = new String("Java");  
String obj2 = new String("Java");  

System.out.println(literal1 == literal2); // true (shared pool memory)  
System.out.println(obj1 == obj2);         // false (different objects)  
System.out.println(obj1.equals(obj2));    // true (content matches)  

2. Custom Objects

By default, .equals() behaves like == unless overridden. Always override .equals() (and hashCode()) for meaningful Java object comparison:

class Person {  
    String name;  
    Person(String name) { this.name = name; }  

    @Override  
    public boolean equals(Object obj) {  
        if (obj instanceof Person) {  
            return this.name.equals(((Person) obj).name);  
        }  
        return false;  
    }  
}  

Person p1 = new Person("Alice");  
Person p2 = new Person("Alice");  
System.out.println(p1 == p2);      // false  
System.out.println(p1.equals(p2)); // true (after overriding)  

Pitfalls to Avoid

1. NullPointerException with .equals()

Calling .equals() on a null object crashes the code:

String s1 = null;  
System.out.println(s1.equals("test")); // Throws NullPointerException  

To fix this issue, either we need to use Objects.equals(s1, "test") or check for null first.

Example:

String s1 = null;  
System.out.println(Objects.equals(s1, "test"));

This prints the output as false.

2. Mixing == and .equals() for Wrapper Classes

Integer a = 127;  
Integer b = 127;  
System.out.println(a == b); // true (cached values)  

Integer c = 200;  
Integer d = 200;  
System.out.println(c == d); // false (outside cache range)  

Key Takeaways

  1. ==: Compares primitive values or object references.
  2. .equals(): Compares object content (override for custom logic).
  3. Strings: Always use .equals() for Java string comparison.
  4. Null Safety: Prefer Objects.equals() to avoid NullPointerException.

Conclusion

Mastering the difference between == and .equals() in Java is essential for writing bug-free code. Use == for primitives and memory-based checks, and rely on .equals() for logical Java object comparison. Always override .equals() in custom classes and stay cautious with == vs .equals() in Java scenarios involving strings or wrapper objects.

By applying these principles, you’ll avoid common pitfalls and ensure accurate comparisons in your Java projects.

Related Posts:

  • Control Statements in Java
  • Primitive data types in Java
  • What is Java? Exploring Its Key Features, Benefits,…
  • What Is Java Swing? A Complete Guide to Java’s GUI Toolkit
  • Top 10 Common Java Errors
  • Arrays of Primitive Types in Java
Tags:javalanguage-fundamentals
Was this article helpful?
← Previous ArticleWhat is Autoboxing and Unboxing in Java?
Next Article →Switch Statement with Strings in Java

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