티스토리 뷰

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

이렇게 에러없이 출력될 것이다.

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함