Java == vs equals() Method

📌 Difference Between == and .equals() in Java If you're preparing for a Java interview, this question will definitely come: It sounds basic. But many developers still get it wrong. 🔎 == Operator == compares references (memory addresses) when used with objects. Example: String s1 = new String("Java"); String s2 = new String("Java"); System.out.println(s1 == s2); 👉 Output: false Because: - Two different objects in heap - Different memory locations 🔎 .equals() Method .equals() compares content (value), not memory address. System.out.println(s1.equals(s2)); 👉 Output: true Because: Both contain the same text "Java" ⚠️ Important Clarification For primitive types: int a = 10; int b = 10; System.out.println(a == b); int a = 10; int b = 10; System.out.println(a == b); Here == compares actual values → true .equals() is not used for primitives. 🔥 Real-World Impact - Using == instead of .equals() can cause: - Subtle bugs - Wrong business logic - Failed comparisons in collections #Java #InterviewPreparation #SoftwareEngineering #JavaDeveloper #Programming

  • No alternative text description for this image

👉 Use == for primitives 👉 Use .equals() for objects And always understand what you're comparing — reference or value.

Like
Reply

To view or add a comment, sign in

Explore content categories