1Z0-811 · Question #31
Given the code fragment: String s1 = "foo-bar"; String s2 = new String ("foo-bar"); System.out.print (s1.equals(s2) + " "); System.out.print (s1 == s2); System.out.print (" " + s1.compareTo (s2))…
The correct answer is B. true false 0. Option B is correct because equals() compares string content (both hold "foo-bar", so true), == compares object references (they point to different memory locations, so false), and compareTo() measures lexicographic difference - identical strings yield 0. A is wrong because…
Question
Options
- Afalse false -1
- Btrue false 0
- Ctrue true 0
- Dfalse true -1
How the community answered
(17 responses)- A6% (1)
- B94% (16)
Explanation
Option B is correct because equals() compares string content (both hold "foo-bar", so true), == compares object references (they point to different memory locations, so false), and compareTo() measures lexicographic difference - identical strings yield 0.
A is wrong because equals() returns true (same content), not false, and compareTo() returns 0, not -1. C is wrong because new String("foo-bar") explicitly allocates a new heap object, so s1 == s2 is false even though the content matches - this bypasses the String pool entirely. D is wrong on both equals() (content is identical → true) and == (different objects → false).
Memory tip: Think of == as asking "same object?" and equals() as asking "same value?" - and remember that new String(...) is the one keyword that guarantees a fresh object, making == fail even when content is equal.
Topics
Community Discussion
No community discussion yet for this question.