ocajp 자격증 (Oracle Certified Associate Ja

자바 ocjap 문제 및 해설 - 배열 86

xemaker 2020. 2. 23. 08:39

Given:

package ocjap;

class Student{
String name;
public Student(String name){
this.name=name;
}
}

public class Test86 {
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 ocjap.Test86.main(Test86.java:16)

 

컴파일시 에러는 안나고 실행시 Exception in thread "main" java.lang.NullPointerException 발생.

왜냐하면 0 번째 배열에는 값이 없는데 s.name으로 접근하려고 했기 때문에.

그냥 객체를 바로 찍으면

for (Student s : students) {
//System.out.println(""+s.name);
System.out.println(s);
}

null
ocjap.Student@15db9742
ocjap.Student@6d06d69c

이런식으로 첫번째 인덱스에는 값이 없으니 null 이 찍히고 나머지는 값이 있으니 해쉬코드가 찍힌다.