nerdexam
Oracle

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…

Data Types and Operators

Question

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?

Options

  • A12 10
  • B10 10
  • C9 9
  • D10 14

How the community answered

(50 responses)
  • A
    2% (1)
  • B
    92% (46)
  • C
    2% (1)
  • D
    4% (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, s is 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

#String immutability#String concatenation#String.length()#String methods

Community Discussion

No community discussion yet for this question.

Full 1Z0-811 Practice