Java, NullPointerException

변수에 객체 인스턴스를 할당하게 되면 참조 값을 갖게된다. 만약 이 참조되는 객체에 특정 멤버로 접근 하였는데, 멤버가 없어 NullPointerException 예외가 발생하였다. NullPointerException은 Pointer는 가르키는 용어와 Null 없다는 뜻으로 가리켰더니 말 그대로 객체가 없어서 예외되었다고 개발자에게 알려주는 메시지이다.

NullPointerException 예제1

public class Main {
    public static class Point {
        int x;
        int y = 10;
    }

    public static void main(String[] args) {
        Point p = null;
        p.y = 10;
    }
}

출력:

Exception in thread "main" java.lang.NullPointerException: Cannot assign field "y" because "p" is null
	at Main.main(Main.java:11)

이 문제는 어떤 문제가 있는지 바로 파악이 된다. 많이 발생되는 문제 예시를 살펴보도록 한다.

NullPointerException 예제2

public class Main {
    public static class Draw {
        Point p;
        int count = 0;
    }

    public static class Point {
        int x;
        int y = 10;
    }

    public static void main(String[] args) {
        Draw draw = new Draw();
        System.out.println(draw.count);
        System.out.println(draw.p);

        System.out.println(draw.p.x);
    }
}

출력:

0
null
Exception in thread "main" java.lang.NullPointerException: Cannot read field "x" because "draw.p" is null
	at Main.main(Main.java:19)

IDE 오류가 없다고 판단하고 믿고 실행하였더니 Exception 으로 실행이 종료되었다.
이것은 메모리 상에서 생성된 Draw 클래스 내부에서는 Point 클래스를 아직 메모리로 할당하지 않은 상태로 null 인 것을 확인할 수 있다.
그리고 Point 멤버변수 x 를 접근하게 되면 NullPointerException 에러가 발생하게 된 것이다.

해당 오류의 개선 방법은 draw.p 에서도 인스턴스를 생성하는 new 연산자를 넣어주도록 한다.

public static void main(String[] args) {
    Draw draw = new Draw();
    draw.p = new Point();
    
    System.out.println(draw.count);
    System.out.println(draw.p);

    System.out.println(draw.p.x);
}