Java

[Java] int와 Integer과 null

bornsoon 2025. 5. 3. 23:00
import java.util.PrioirtyQueue;

...

    PriorityQueue<Integer> prioirtyQueue = new PrioirityQueue<>();

    Integer value = priorityQueue.poll();
    
    // poll()은 큐가 비어있을 경우 null 반환
    // int value는 null 값 처리 불가능
    // int로 할 경우, NullPointerException이 발생
    
    if (value == null) {
        // null일 경우
    }

 

컬렉션 자료구조를 사용할 때, 컨테이너가 비어있으면 NullPointException이 발생하는 경우가 종종 있다.

이 때, Integer로 반환받으면 null을 처리할 수가 있다.

 

int는 null 값을 가질 수 없지만, Integer은 null값을 가질 수 있는 이유!

→ int는 기본형(Primitive Type)이지만 Integer은 참조형(Reference Type)이기 때문!!!

 

 

int Integer
자료형 Wrapper 클래스
산술 연상 가능 직접적인 산술 연산 불가능 (Auto Unboxing으로 가능)
null 값 (X) null 값 (O) → SQL 연동할 경우 처리가 용이
초기값 0 초기값 null (클래스 필드의 경우)
/ (지역 변수는 초기화 되지 않으면 컴파일 에러)

 

 

728x90