Exercises · Q7
Q.Why should equals() be used instead of == to compare two strings? Illustrate with a short example.
ChseodishaTextbookSubjectiveImportance★★★★★est
50% · 7/14 Questions
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →The problem. A String is an object, and a string variable actually holds a reference (the location of that object in memory), not the text itself. This makes the two comparison operators behave differently:
==checks whether two references point to the same object in memory..equals()checks whether the two strings contain the same characters.
Example:
String a = new String("Odisha");
String b = new String("Odisha");
System.out.println(a == b); // false -> two different objects
System.out.println(a.equals(b)); // true -> same contents
Explanation. a and b hold the same text, 'Odisha', but new String(...) creates two separate objects in memory. So a == b is false (different objects), while a.equals(b) is true (same characters). Since we almost always want to know whether the text matches, we use equals(). …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.