🔹 Introduction
Understanding the difference between == and equals() is one of the most fundamental Java interview questions.
👉 Interviewers ask this to check your understanding of:
- Memory
- Object comparison
- String handling
🔹 What is == in Java?
== is used to compare memory references (addresses).
👉 It checks:
- Whether two variables point to the same object
🔹 Example Using ==
public class Test {
public static void main(String[] args) {
String a = new String("hello");
String b = new String("hello");
System.out.println(a == b);
}
}
🔹 Output
false
👉 Because both objects are stored in different memory locations
🔹 What is equals() in Java?
equals() is used to compare actual content (values).
🔹 Example Using equals()
public class Test {
public static void main(String[] args) {
String a = new String("hello");
String b = new String("hello");
System.out.println(a.equals(b));
}
}
🔹 Output
true
👉 Because values are the same
🔍 Important Interview Scenario
String x = "java";
String y = "java";
System.out.println(x == y);
🔹 Output
true
👉 Why?
Because of String Constant Pool
Both variables point to same memory
⚡ Key Differences
| Feature | == | equals() |
|---|---|---|
| Comparison | Memory reference | Content/value |
| Used for | Primitives + Objects | Objects only |
| Overridable | No | Yes |
🔹 When to Use What?
✔ Use ==
- For primitive types
- For reference comparison
✔ Use equals()
- For comparing object values
🔹 Common Mistake
❌ Using == for String comparison
👉 Leads to wrong results
🔹 Time Complexity
-
O(1) for
== -
O(n) for
equals()(depends on object)
🔹 Key Takeaways
✔ == → compares memory
✔ equals() → compares value
✔ String pool affects behavior
✔ Very frequently asked interview question
🔹 Conclusion
Understanding == vs equals() is essential for writing correct Java programs and performing well in interviews.
🔗 Also Read
👉 First Non-Repeating Character in Java
👉 Check Palindrome String in Java
👉 Reverse a String
👉 Count Character Frequency in Java
👉 Separate Even and Odd Numbers Using Streams
👉 Find Duplicate Characters in a String
👉 Check Palindrome String in Java
👉 Reverse a String
👉 Count Character Frequency in Java
👉 Separate Even and Odd Numbers Using Streams
👉 Find Duplicate Characters in a String
Comments
Post a Comment