Given the code fragment:
Which code fragment prints red:blue:small:medium?
A.
B.
C.
D.
Given the code fragment:
Which code fragment prints red:blue:small:medium?
A.
B.
C.
D.
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.
If D: ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2! the correct answer is C!
C is the correct one
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++; // } } }
ANSWER IS C!
C is the answer for me
c is answer
C is correct
C is the correct answer!
C is the correct one!
Correct option is C
correct answer:C
Source code.
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] + ":" ); } } */
/* 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++; } */ }
Tested, answer is only C. A and B, didnt print anything. D throws Exception (ArrayIndexOutOfBoundsException).
Rewriting, A didn't print anything. B prints only "small:"
Could anyone explain why B is not correct? I tested it, and it showed the exactly same result as C (red:blue:small:medium:).
For me, B option returned only "small:"
for the first comparison where index = 0 and idx = 0 the condition idx < index will fail iteself.
only C D is incorrect: red:blue:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2