| 원시 타입 | Wrapper 클래스 |
|---|---|
int |
Integer |
long |
Long |
boolean |
Boolean |
double |
Double |
char |
Character |
null 값 표현 가능
private Integer age; // null 값 가능
private int age; // null 값 불가능(변수 사용할 때 NPE 발생)
null을 가질 수 없지만 Wrapper 타입은 객체이므로 null 값을 가질 수 있음Hibernate, JPA 등 ORM 프레임워크 사용 시 필수
@Entity
public class User {
@Column(nullable = true)
private Integer age;
}
null로 매핑되는데, 원시 타입은 이를 표현할 수 없기 때문null 값을 가질 수 있도록 해야함Collection에는 객체만 저장 가능(원시 타입은 저장 불가능)
List<Interger> scores = new ArrayList<>(); // O
List<int> scores = new ArrayList<>(); // X
Optional, Generic 등과 함께 사용 가능
// Optional 적용 예제
Optional<Interger> maybeAge = Optiona.ofNullable(age);
// Generic 적용 예제
List<Integer> ages = new ArrayList<>();
Boxing/Unboxing 지원으로 개발 편의성
Interger age = 25; // auto boxing
int realAge = age; // auto-unboxing
| 상황 | 권장 타입 |
|---|---|
| DB null 허용, 값이 Optional할 수 있음 | Wrapper |
| 값이 항상 존재해야 함 (성능 최우선) | Primitive |
| 제네릭, Optional 등과 함께 사용 | Wrapper |
| 단순 계산 목적, 기본값이 꼭 필요 | Primitive |