ocajp 문제 해설 - DoWhile 89
Given the code fragment:
public class DoWhile89 {
public static void main(String[] args) {
int[] arr= {1,2,3,4};
int i=0;
do {
System.out.print(arr[i]+" ");
i++;
}while(i < arr.length - 1);
}
}
What is the result?
A. 1 2 3 4
followed by an ArrayIndexOutOfBoundsException
B. 1 2 3
C. 1 2 3 4
D. Compilation fails
해설:
아래 코드를 보면 이해가 쉬울듯 합니다.
public class DoWhile89 {
public static void main(String[] args) {
int[] arr= {1,2,3,4};
int i=0;
do {
System.out.println("증가전 i="+ i);
System.out.println(arr[i]+" ");
i++;
System.out.println("증가 후 i="+ i);
System.out.println();
}while(i < arr.length - 1);
}
}
결과
증가전 i=0
1
증가 후 i=1
증가전 i=1
2
증가 후 i=2
증가전 i=2
3
증가 후 i=3
첫번째 루프: i가 0 부터 시작해서 인덱스가 1인 배열값을 프린트하고(1) 1증가 while문과 비교(1<4-1,즉 1<3) true
두번째 루프: i가 1 부터 시작해서 인덱스가 2인 배열값을 프린트하고(2) 1증가 while문과 비교(2<4-1,즉 2<3) true
두번째 루프: i가 2 부터 시작해서 인덱스가 3인 배열값을 프린트하고(3) 1증가 while문과 비교(3<4-1,즉 3<3) false
끝.
결과:
1 2 3
정답: B