104k views
0 votes
Consider the following code segment.

String str = "AP-CSA";
for (int i = 0; i < str.length(); i++)
{
if (str.substring(i, i + 1).equals("A"))
{
System.out.print(i + " ");
}
}
What is printed as a result of executing the code segment?
A. 0
B. 5
C. 0 5
D. 0 6
E. 1 6

User Edofic
by
8.5k points

1 Answer

5 votes

Final answer:

The code checks each character in the string "AP-CSA" and prints the indices where 'A' appears, which are at the start and near the end of the string, resulting in the output "0 5 ".

Step-by-step explanation:

The code segment is designed to identify and print out the indexes of the character 'A' within the string "AP-CSA". The for loop iterates over each character index of the string using str.length() to determine the loop's range.

During each iteration, the code checks if the single-character substring starting at the current index (i) is equal to 'A' using str.substring(i, i + 1).equals("A"). If this condition is true, the current index i is printed followed by a space.

For the string "AP-CSA", the letter 'A' appears at index 0 and index 5. Therefore, the output of the code segment will be "0 5 ", indicating that the character 'A' is found at these positions in the given string.

User Topher Hunt
by
8.4k points