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)…
Question
Options
- Atrue true
- Btrue false
- Cfalse false
- Dfalse true
How the community answered
(30 responses)- B3% (1)
- C93% (28)
- D3% (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 betrue, which would only happen ifstrwere actually modified bytrim()- it isn't. - D (false true) requires
str.isEmpty()to betrue, butisEmpty()checkslength() == 0; the unretrievedtrim()result never changesstr.
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
Community Discussion
No community discussion yet for this question.