Java Interview Prep: The Difference Between == and .equals()


Understanding the difference between the == operator and .equals() method in Java is important for Java interview preparation. Here’s a simple explanation along with common questions.

1. == Operator (Reference Comparison)

  • Purpose: Compares references (memory locations) of two objects.

  • How it works: It checks if both variables refer to the exact same object in memory.

  • For primitive types, == compares the actual values.

    Example with Objects:

    String s1 = new String("Hello");
    String s2 = new String("Hello");
    System.out.println(s1 == s2); // false, because they are different objects in memory
    

    Example with Primitives:

    int a = 5;
    int b = 5;
    System.out.println(a == b); // true, because the values are the same

2. .equals() Method (Content Comparison)

  • Purpose: Compares the content or values of two objects.

  • How it works: It checks if the actual data inside two objects is the same (this method is often overridden in classes like String to compare values).

    Example:

    String s1 = new String("Hello");
    String s2 = new String("Hello");
    System.out.println(s1.equals(s2)); // true, because the contents are the same

Key Difference:

  • == checks if both objects are the same in memory.
  • .equals() checks if two objects have the same value.

Common Interview Questions for Freshers

1. What is the difference between == and .equals() in Java?

  • Answer:
    • == checks if two references point to the same object in memory.
    • .equals() checks if two objects have the same content or value.

2. When should you use == and when should you use .equals()?

  • Answer:
    • Use == to compare primitive types or to check if two object references are the same.
    • Use .equals() to compare the values of objects, especially String or other custom objects that override .equals().

3. Can == be used to compare two String objects in Java?

  • Answer:
    • Using == to compare String objects will only return true if they are the same object in memory. It's better to use .equals() to compare the contents of the strings.

Comments

Popular posts from this blog

Spring Boot OpenAI Integration: Step-by-Step Guide

Orchestration-Based Saga Architecture and Spring Boot Microservices Implementation Guide

Spring Boot 3 + Angular 15 + Material - Full Stack CRUD Application Example