85.1k views
0 votes
What is stored in str after the following code executes?

String str = "Computer Science";
int i = 0;
while (i < 8)
{
if (str.indexOf("m") < i)
{
str = str.substring(0, 2) + str;
}
i += 2;
}

User MarkoHiel
by
7.7k points

1 Answer

3 votes

Answer:

"CoCoComputer Science"

Step-by-step explanation:

First let's understand how the loop works, then we'll see what it does.

The variable i is initialized to value 0. Then inside the loop, it's incremented by 2 in each loop passage, while i < 8, so the loop will be processed with the following values of i: 0, 2, 4 and 6. It will run a total of 4 times.

Let's examine the actions done during the FIRST loop:

(str equals "Computer Science", so indexOf('m') = 2, i = 0)

- if the index of 'm' within the string is < i (index = 2, i = 0, FALSE)

does nothing

increases value of i by 2 (now i = 2)

Let's examine the actions done during the SECOND loop:

(str equals "Computer Science", so indexOf('m') = 2, i = 2)

- if the index of 'm' within the string is < i (index = 2, i = 2, FALSE)

does nothing

increases value of i by 2 (now i = 4)

Let's examine the actions done during the THIRD loop:

(str equals "Computer Science", so indexOf('m') = 2, i = 4)

- if the index of 'm' within the string is < i ( index = 2, i = 4, TRUE)

then str becomes "CoComputer Science"

increases value of i by 2 (now i = 6)

Let's examine the actions done during the FOURTH loop:

(str equals "CoComputer Science", so indexOf('m') = 4, i = 6)

- if the index of 'm' within the string is < i (index = 4, i = 6, TRUE)

then str becomes "CoCoComputer Science"

increases value of i by 2 (now i=8)

Loop ends because i = 8 (i < 8 becomes false)

User Joseph Siefers
by
8.1k points