nerdexam
Oracle

1Z0-811 · Question #71

Given: String test = "a"; for (; test.compareTo ("aaa") == 0; test = test + "a") { System.out.print (test.length () + " "); System.out.print (test); } What is the output?

The correct answer is D. a. Option D is correct because the for loop's condition - test.compareTo("aaa") == 0 - is evaluated before the first iteration. Since test starts as "a", and "a".compareTo("aaa") returns a negative number (not 0), the condition is immediately false, and the loop body never…

Control Flow

Question

Given: String test = "a"; for (; test.compareTo ("aaa") == 0; test = test + "a") { System.out.print (test.length () + " "); System.out.print (test); } What is the output?

Options

  • A1 2 3 aaa
  • B1 2 aaa
  • CCompilation fails
  • Da

How the community answered

(20 responses)
  • A
    5% (1)
  • B
    5% (1)
  • C
    15% (3)
  • D
    75% (15)

Explanation

Option D is correct because the for loop's condition - test.compareTo("aaa") == 0 - is evaluated before the first iteration. Since test starts as "a", and "a".compareTo("aaa") returns a negative number (not 0), the condition is immediately false, and the loop body never executes. test retains its initial value of "a", which is the only value ever associated with the variable.

Why distractors are wrong:

  • A and B assume the loop runs one or more times, printing length values and the string contents - this never happens because the loop exits before the body is ever reached.
  • C is wrong because the code is perfectly valid Java; an empty for-loop initializer is legal, and all method calls are correct.

Memory tip: Think of compareTo() as a difference calculator - it returns 0 only when the two strings are identical (like a "tie"). Here the loop is waiting for test to already be "aaa" before it will even start - but since it begins as "a", the gate never opens.

Topics

#String.compareTo()#for loop conditions#loop execution#String comparison

Community Discussion

No community discussion yet for this question.

Full 1Z0-811 Practice