☑️ Java: equals() vs == What’s the Difference?

Pushkar RoyPushkar Roy
3 min read

When learning Java, you’ll regular see == operator and .equals() used to compare values. They look similar, but they work very differently.

In this post, we'll cover:

✅ What == really does
✅ How .equals() is different
✅ Use cases with int, float, String, and custom objects
✅ Which one compares type and value, and which compares only value
✅ tips to avoid mistakes


🔍 What Does == Do in Java?

In Java, == operators behaves differently depending on what you're comparing:

🧱 For primitive types (int, float, char, etc.)

== operators checks both type and value.

int a = 10;
int b = 10;
System.out.println(a == b); // true (same type, same value)

float f = 10.0f;
System.out.println(a == f); // true (converted to same numeric value)

System.out.println(a == 10.0); // true (int is promoted to double)

So, with primitives, == checks value (and types must be compatible for comparison).

📦 For objects, including String, arrays, or custom classes:

== operators compares references, i.e., whether two variables point to the exact same object in memory.

String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1 == s2); // false why ?? ( because both are different objects)

String s3 = "hello";
String s4 = "hello";
System.out.println(s3 == s4); // true (same memory location and value)

🔸 What is .equals() in Java?

👉 .equals() checks if two objects have the same value

  • You use .equals() to compare the content inside objects.
String s1 = new String("hello");
String s2 = new String("hello");

System.out.println(s1.equals(s2)); // true

.equals() works well with strings, numbers (like Integer), and collections (like ArrayList).

📦 Comparing int, float, and String

🔹 int and float (primitive values)

int x = 5;
int y = 5;
System.out.println(x == y); // ✅ true
// x.equals(y); ❌ Error – can't use equals() with primitives

🔹 Integer (object)

Integer x = 100;
Integer y = 100;
System.out.println(x == y);      // ✅ true (Java caches small numbers)
System.out.println(x.equals(y)); // ✅ true

Integer a = 200;
Integer b = 200;
System.out.println(a == b);      // ❌ false (outside catch ranges i.e +128 to -127)
System.out.println(a.equals(b)); // ✅ true

Java caches Integer objects from -128 to 127. Beyond that, different objects are created.

🔹 String

String a = "hi";
String b = "hi";
System.out.println(a == b);      // ✅ true (same memory)
System.out.println(a.equals(b)); // ✅ true

String s1 = new String("hi");
String s2 = new String("hi");
System.out.println(s1 == s2);      // ❌ false (different objects)
System.out.println(s1.equals(s2)); // ✅ true

🧑‍💻 Custom Objects

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

Person p1 = new Person("Alice");
Person p2 = new Person("Alice");

System.out.println(p1 == p2);        // ❌ false (different objects)
System.out.println(p1.equals(p2));   // ❌ false (not overridden yet)

To compare values of both objects , we have to override .equals().

@Override
public boolean equals(Object obj) {
    Person other = (Person) obj;
    return this.name.equals(other.name);
}

Now:

System.out.println(p1.equals(p2));   // ✅ true

🧠 Summary Table(refrence from chatgpt)

Feature==.equals()
Works onPrimitives and ObjectsObjects only
ComparesMemory (address) or value (primitives)Actual content (values)
With stringsChecks same memoryChecks text content
Null-safe❌ No (can throw error)✅ Yes, if used like "text".equals(x)
Can override?❌ No✅ Yes

⚠️ Quick Tips

  • Use == for int, float, char, etc.

  • Use .equals() for String, Integer, custom objects, etc.

  • For safe string checks:
    Use "yes".equals(userInput) instead of userInput.equals("yes") – this avoids null errors.


✅ Final Thought

Remember:

  • Use == to compare memory or primitive values

  • Use .equals() to compare object content

It’s a small difference, but very important to avoid bugs in your code!

Thank you for reading! 🙌

0
Subscribe to my newsletter

Read articles from Pushkar Roy directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Pushkar Roy
Pushkar Roy

Hey 👋 I am Pushkar , I am learning person holding skills in Developing UI as well as backend using NodeJS and a passionate programmer who loves to code. I am creatively curious and a self-learner and self-motivated person who believes in smart work achieved from hard work . 🚀 Currently, my focus is on Full Stack Development, where I engage in daily practice of Data Structures and Algorithms and exploring web3 and new technologies. I’m also active in Open Source and looking forward to contributing to Open-Source Projects. ✨Proficient in Data Structures and Algorithms with a strong command of C++. 💻Front-end development expertise using ReactJS and NextJS with MySQL, ExpressJs ensuring the creation of fully responsive and scalable websites. 🌐Currently, I am focusing on JavaScript, TypeScript, NodeJS, React, NextJs and Data Structure. Let's connect if you share the love for coding, learning, and building cool things! 🤝