Java 래퍼 - 오토박싱, 언박싱

박싱 언박싱에서 Int형을 Integer 객체로 변환하거나 Integer 객체를 Int 기본형으로 반환하는 방법을 살펴보았다.

public class Main {
    public static void main(String[] args) {
        // Primitive -> Wrapper
        int value = 111;
        Integer boxed = Integer.valueOf(value);
        
        // Wrapper -> Primitive
        int unboxed = boxed.intValue();

        System.out.println(boxed);
        System.out.println(unboxed);
    }
}

111
111

예제코드의 박싱은 Integer.valueOf() 객체의 메소드를 사용하면 Integer 객체로 값을 할당하므로 사용하였다.
언박싱은 박싱된 Integer 변수의 intValue() 메소드로 기본형 타입 변수로 반환하기에 기본형 변수에게 할당하였다.

객체와 기본형 변수 변환은 굉장히 오랫동안 사용했고 메소드를 직접 불려야하는 불편함이 있었다.


오토 박싱 (Auto-Boxing), 오토 언박싱(Auto-Unboxing)

Integer.valueOf(...) 메소드를 사용하여 박싱하였는데 매번 메소드를 불려와 불편함을 일으키고 싶지 않았던 개발자들은 자바 1.5 부터 오토 박싱을 지원하게 되었다.

public class Main {
    public static void main(String[] args) {
        int value = 111;

        // Primitive -> Wrapper
        Integer boxed = Integer.valueOf(value);
        Integer autoBoxed = value; // 오토 박싱 (Auto-boxing)

        // Wrapper -> Primitive
        int unboxed = boxed.intValue();
        int autoUnboxed = boxed; // 오토 언박싱 (Auto-unboxing)

        System.out.println(autoBoxed);
        System.out.println(autoUnboxed);
    }
}

111
111

Could not load content