자바에서 null 값을 참조할 때 발생하는 런타임 예외

 

NPE가 발생하는 대표적인 상황

1. null 객체의 메서드를 호출할 때

String str = null;
System.out.println(str.length()); // ❌ NPE 발생

 

 

2. null 객체의 필드에 접근할 때

class Person {
    String name;
}

public static void main(String[] args) {
    Person p = null;
    System.out.println(p.name); // ❌ NPE 발생
}

 

 

3. null을 배열처럼 사용하려 할 때

int[] arr = null;
System.out.println(arr.length); // ❌ NPE 발생

 

 

4. null을 포함한 equals() 호출

String input = null;
if (input.equals("exit")) {  // ❌ NPE 발생
    System.out.println("프로그램 종료");
}
if ("exit".equals(input)) {  // ✅ NPE 방지 - 상수값을 앞에 두고 비교
    System.out.println("프로그램 종료");
}

 

 

5. null 값을 unboxing할 때 (Wrapper 클래스)

Integer num = null;
int value = num; // ❌ NPE 발생 (null을 int로 변환 불가)

'개발 지식' 카테고리의 다른 글

프로세스와 스레드의 동작 원리  (0) 2025.03.23
웹서버 애플리케이션 관점에서의 Thread Pool  (0) 2025.03.21
JVM 메모리 구조  (0) 2025.02.25
이스케이프 시퀀스  (0) 2025.02.22
NumberFormat 런타임 에러  (0) 2025.02.21