1Z0-811 · Question #19
Given the code fragment: String s = "Hello Java"; System.out.println (s.length()); s.concat ("SE 8"); System.out.println (s.length ()); What is the result?
The correct answer is B. 10 10. Option B is correct because Java String objects are immutable - s.concat("SE 8") returns a new String object but does not modify s, and since the return value is discarded (not assigned back to s), s still points to "Hello Java" (length 10) for both println calls. Why…
Question
Options
- A12 10
- B10 10
- C9 9
- D10 14
How the community answered
(50 responses)- A2% (1)
- B92% (46)
- C2% (1)
- D4% (2)
Explanation
Option B is correct because Java String objects are immutable - s.concat("SE 8") returns a new String object but does not modify s, and since the return value is discarded (not assigned back to s), s still points to "Hello Java" (length 10) for both println calls.
Why distractors are wrong:
- A (12, 10): 12 is not the length of any string involved here;
"Hello Java"has exactly 10 characters. - C (9, 9): Off-by-one error -
"Hello Java"is 10 characters including the space, not 9. - D (10, 14): This would be correct if the code read
s = s.concat("SE 8")-"Hello JavaSE 8"is 14 characters - but without reassignment,sis never updated.
Memory tip: In Java, think of String methods as returning a receipt - if you don't save the receipt (s = s.concat(...)), the transaction is lost. The original string never changes.
Topics
Community Discussion
No community discussion yet for this question.