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:
Example with Primitives:
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
Stringto compare values).Example:
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, especiallyStringor other custom objects that override.equals().
- Use
3. Can == be used to compare two String objects in Java?
- Answer:
- Using
==to compareStringobjects will only returntrueif they are the same object in memory. It's better to use.equals()to compare the contents of the strings.
- Using
Comments
Post a Comment