Exam 1z0-808 All QuestionsBrowse all questions from this exam
Question 18

Given the code fragment:

Which code fragment prints red:blue:small:medium?

A.

B.

C.

D.

    Correct Answer:

    The correct answer is C. The code in option C correctly iterates through all elements of the 2D array 'shirts' using a foreach loop and prints each element separated by a colon. The loops in options A, B, and D either do not access all elements in the correct order or result in an ArrayIndexOutOfBoundsException.

Discussion
RoxyFoxy

If D: ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2! the correct answer is C!

Vicky_65

C is the correct one

[Removed]

Answer is C class HelloWorld { public static void main(String[] args) { String shirts[][] = new String[2][2]; //shirts[3][1] = "red"; //java.lang.ArrayIndexOutOfBoundsException shirts[0][0] = "red"; shirts[0][1] = "blue"; shirts[1][0] = "small"; shirts[1][1] = "medium"; for(String[] c : shirts){ //red:blue:small:medium: for(String s : c){ System.out.println(s + ":"); } } // for(int index = 0; index <= 2;){ //red: blue: java.lang.ArrayIndexOutOfBoundsException // for(int idx=0; idx<=2;){ // System.out.println(shirts[index][idx] + ":"); // idx++; // } // index++; // } } }

amigo31

ANSWER IS C!

willokans

C is the answer for me

anmoldev2java

c is answer

z24134

C is correct

DarGrin

C is the correct answer!

duydn

C is the correct one!

Sreeni_A

Correct option is C

morgan3987

correct answer:C

carloswork

Source code.

carloswork

public static void main(String[] args) { String shirts[][] = new String[2][2]; shirts[0][0] = "red"; shirts[0][1] = "blue"; shirts[1][0] = "small"; shirts[1][1] = "medium"; /* A for (int index = 1; index < 2 ; index++) { for (int idx = 1; idx < index ; idx++) { System.out.print(shirts[index][idx] + ":" ); } } */ /* B for (int index = 0; index < 2 ; ++index) { for (int idx = 0; idx < index ; ++idx) { System.out.print(shirts[index][idx] + ":" ); } } */

carloswork

/* C */ for (String [] c : shirts) { for (String s : c) { System.out.print(s + ":"); } } /* D System.out.println(); for (int index = 0; index <= 2; ) { for (int idx = 0; idx <= 2; ) { System.out.print(shirts[index][idx] + ":" ); idx++; } index++; } */ }

carloswork

Tested, answer is only C. A and B, didnt print anything. D throws Exception (ArrayIndexOutOfBoundsException).

carloswork

Rewriting, A didn't print anything. B prints only "small:"

hhuo

Could anyone explain why B is not correct? I tested it, and it showed the exactly same result as C (red:blue:small:medium:).

carloswork

For me, B option returned only "small:"

anmoldev2java

for the first comparison where index = 0 and idx = 0 the condition idx < index will fail iteself.

wk8b

only C D is incorrect: red:blue:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2