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

πŸ‘¨‍πŸ’» How I Started Learning Java at 15 (and You Can Too)

  When I first heard of Java, I thought it was just something to do with Minecraft mods or Android apps. I didn’t realize it would become my...