nerdexam
Oracle

1Z0-808 · Question #47

QUESTION 58 Given the code fragment: public static void main(String[] args) { String str = " "; str.trim(); System.out.println(str.equals("") + " " + str.isEmpty()); } What is the result?

The correct answer is C. false false. Option C is correct because String objects in Java are immutable - str.trim() returns a new trimmed string but the result is thrown away, leaving str still pointing to " " (a single space). Since str remains " ", str.equals("") returns false (a space is not an empty string)…

Working with Selected Classes from the Java API

Question

QUESTION 58 Given the code fragment: public static void main(String[] args) { String str = " "; str.trim(); System.out.println(str.equals("") + " " + str.isEmpty()); } What is the result?

Options

  • Atrue true
  • Btrue false
  • Cfalse false
  • Dfalse true

How the community answered

(30 responses)
  • B
    3% (1)
  • C
    93% (28)
  • D
    3% (1)

Explanation

Option C is correct because String objects in Java are immutable - str.trim() returns a new trimmed string but the result is thrown away, leaving str still pointing to " " (a single space). Since str remains " ", str.equals("") returns false (a space is not an empty string), and str.isEmpty() also returns false (its length is 1, not 0).

Why the distractors fail:

  • A (true true) and B (true false) both require str.equals("") to be true, which would only happen if str were actually modified by trim() - it isn't.
  • D (false true) requires str.isEmpty() to be true, but isEmpty() checks length() == 0; the unretrieved trim() result never changes str.

Memory tip: In Java, String methods never modify the original - they return a new value. If you don't capture the return value (str = str.trim()), nothing changes. A common exam trap is calling a String method and assuming the original variable was updated.

Topics

#String immutability#trim() method#equals() method#isEmpty() method

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice