ocjap 문제 해설 - Array86
class Student{
String name;
public Student(String name) {
this.name=name;
}
}
public class Array86 {
public static void main(String[] args) {
Student[] students = new Student[3];
students[1]=new Student("Richard");
students[2]=new Student("Donald");
for (Student s : students) {
System.out.println(""+s.name);
}
}
}
What is the result?
A. null
Richard
Donald
B. Richard
Donald
C. Compilation fails.
D. An ArrayIndexOutOfBoundsException is thrown at runtime.
E. A NullPointerException is thrown at runtime.
정답: E
결과:
Exception in thread "main" java.lang.NullPointerException
at Array86.main(Array86.java:14)
해설:
Student 배열의 0번째 배열에는 값이 없는데 접근하려고 하니 NullPointerException 에러가 발생한다.
객체 배열도 초기화가 필요하다. 초기화 없이 사용하려고 하면 NullPointerException 이 발생한다.
만약 0번째 요소에도 아래와 같이 값을 넣어주면
students[0]=new Student("Richard");
class Student{
String name;
public Student(String name) {
this.name=name;
}
}
public class Array86 {
public static void main(String[] args) {
Student[] students = new Student[3];
students[0]=new Student("Richard");
students[1]=new Student("Richard");
students[2]=new Student("Donald");
for (Student s : students) {
System.out.println(""+s.name);
}
}
}
결과:
Richard
Richard
Donald
이렇게 에러없이 출력될 것이다.