1Z0-808 · Question #9
Given the code fragment: public class App { public static void main(String[] args) { String str1 = "Java"; String str2 = new String("Java"); //line n1 { System.out.println("Equal"); } else {…
The correct answer is B. if (str1.equalsIgnoreCase(str2)). Option B works because equalsIgnoreCase() compares the content of two String objects character by character (ignoring case), not their memory locations - so "Java" equals "Java" regardless of how each String was constructed. Option A fails because str3 = str2 just copies the…
Question
Options
- AString str3 = str2; if (str1 == str3)
- Bif (str1.equalsIgnoreCase(str2))
- CString str3 = str2; if (str1.equals(str3))
- Dif (str1.toLowerCase() == str2.toLowerCase())
How the community answered
(22 responses)- A5% (1)
- B95% (21)
Explanation
Option B works because equalsIgnoreCase() compares the content of two String objects character by character (ignoring case), not their memory locations - so "Java" equals "Java" regardless of how each String was constructed.
Option A fails because str3 = str2 just copies the reference to the heap-allocated new String("Java") object; == then compares memory addresses, not content, so str1 (pool) and str3 (heap) point to different objects.
Option D fails for the same == trap: toLowerCase() creates new String objects each time, so both results land on the heap at different addresses - == returns false even though the characters match.
Option C is worth noting: str1.equals(str3) actually would also print Equal, since equals() is content-based. This appears to be a flaw in the exam question - both B and C are technically correct. If forced to choose, B is the "safest" answer because equalsIgnoreCase() is unambiguously content-based.
Memory tip: In Java, == asks "same object?" while .equals() / .equalsIgnoreCase() asks "same content?" - always use .equals() for String value comparison, never ==.
Topics
Community Discussion
No community discussion yet for this question.