Tuesday, 10 June 2025

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

 

In Java, you might think == and .equals() do the same thing — but they don’t.

Let’s break down the difference in a super simple way πŸ‘‡

== Operator

  • Compares references (memory addresses).

  • Checks if two variables point to the same object in memory.
    Example:

    String a = new String("Java");

    String b = new String("Java");


    System.out.println(a == b);  // false ❌

    .equals() Method

    • Compares the actual content (data inside the object).

    • Works for objects like String, ArrayList, etc.

No comments:

Post a Comment

πŸš€ Top 3 Java Projects Every Beginner Should Build (With Code Ideas)

 Tired of just printing "Hello World"? It’s time to build something real. πŸ’» If you're learning Java and want to stand out, ...