Consider the following recursive method. public static void whatsItDo(String str) { int len = str.length(); if(len > 1) { String temp = str.substring(0, len – 1); whatsItDo(temp); System.out.println(temp); } } What is printed as a result of the call whatsItDo("WATCH")?

(A) WATC
WAT
WA
W
(B)WATCH
WATC
WAT
WA
(C)W
WA
WAT
WATC
(D)W
WA
WAT
WATC
WATCH
(E)WATCH
WATC
WAT
WA
W
WA
WAT
WATC
WATCH

Respuesta :

Answer:

The answer is C.

W

WA

WAT

WATC

Explanation:

When the recursive method is called using whatsItDo("WATCH"), it works like this:

First the length of the argument is gotten and assigned to len.

Next if the length is greater than 1, execution enter the defined block

Inside the block, a substring is created from the beginning to less than 1 the end (0 to len - 1) and it is assigned to temp.

Then, the method is called again with whatsItDo("WATC").

The iteration continue and the next called method is whatsItDo("WAT"), followed by whatsItDo("WA"), followed by whatsItDo("W").

When whatsItDo("W") is called the condition will fail. So, the execution will pick up from:

whatsItDo("WA") where "W" will be displayed, then

whatsItDo("WAT") where "WA" will be displayed, then

whatsItDo("WATC") where "WAT" will be displayed, then

whatsItDo("WATCH") where "WATC" will be displayed.

And the program will finished execution.