1Z0-809 · Question #95
Given: public class Test3 { public static void main(String[] args) { String names[] = new String[3]; names[0] = "Marry Brown"; names[1] = "Nancy Red"; names[2] = "Jessy Orange"; for (String n…
The correct answer is A. Marrown String out of limits JessOran. Option A is correct because the for-each loop processes all three names, and the outcome depends on each string's length relative to the substring(6, 10) call, which requires the string to have at least 10 characters. "Mary Brown" (10 chars): both substring(0,3) → "Mar" and…
Question
Options
- AMarrown String out of limits JessOran
- BMarrown String out of limits
- CMarrown String out of limits
- DMarrown NanRed JesOran
How the community answered
(37 responses)- A84% (31)
- B11% (4)
- C3% (1)
- D3% (1)
Explanation
Option A is correct because the for-each loop processes all three names, and the outcome depends on each string's length relative to the substring(6, 10) call, which requires the string to have at least 10 characters.
- "Mary Brown" (10 chars): both
substring(0,3)→"Mar"andsubstring(6,10)→"rown"succeed → prints"Marrown" - "Nancy Red" (9 chars):
substring(6,10)attempts to read index 9, which doesn't exist →StringIndexOutOfBoundsExceptionis caught → prints"String out of limits" - "Jessy Orange" (12 chars): both substrings succeed → prints the concatenated result (e.g.,
"JessOran")
B and C are wrong because they only show 2 lines of output - the loop runs all 3 iterations, so 3 lines must always be printed (two valid results + one caught exception). D is wrong because it shows all three names succeeding, but "Nancy Red" is only 9 characters and cannot satisfy substring(6, 10) - an exception is unavoidable.
Memory tip: For substring(start, end), the string must have length >= end. Count the characters in each string and compare to the end index - if the string falls short, a StringIndexOutOfBoundsException fires.
Community Discussion
No community discussion yet for this question.