Java == vs equals() Method: Understanding Reference vs Logical Equality

❌ == is NOT the same as equals() in java They look similar, but they answer two different questions. 🔸== operator Checks reference equality ➡️ Do both variables point to the same object? 🔸equals() method Checks logical equality ➡️ Do both the objects have same value/content? ☘️ Example String a = new String("Java"); String b = new String("Java"); System.out.println(a == b); // false (different objects) System.out.println(a.equals(b)); // true (same content) Even though the text is the same, a and b are stored at different memory locations. 💡Thumb Rule 🔸Use == for primitive types (int, double, boolean) 🔸Use equals for objects (String, custom classes) Getting this wrong can cause subtle bugs, especially when comparing Strings. #Java #SoftwareEngineering #Cleancode #Programming

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories