본문 바로가기

프로그래밍언어/Java

[Java 중급] 오토 박싱

오토 박싱 - Autoboxing


public class AutoboxingMain1 {
    public static void main(String[] args) {
        //Primitive -> Wrapper
        int value = 7;
        Integer boxedValue = Integer.valueOf(value);
        
        //Wrapper -> Primitive
        int unboxedValue = boxedValue.intValue();

        System.out.println("boxedValue = " + boxedValue);
        System.out.println("unboxedValue = " + unboxedValue);
        
    }
}

 

 

자바 5부터 오토박싱 기능을 제공한다. 

public class AutoboxingMain2 {
    public static void main(String[] args) {
        //Primitive -> Wrapper
        int value = 7;
        Integer boxedValue = value;

        //Wrapper -> Primitive
        int unboxedValue = boxedValue;

        System.out.println("boxedValue = " + boxedValue);
        System.out.println("unboxedValue = " + unboxedValue);

    }
}

 

오토 박싱, 언박싱은 컴파일러가 valueOf, xxValue() 등의 코드를 자동으로 추가해주는 기능이다. 

 

 

 

* 인프런 '김영한의 실전 자바 - 중급 1편'을 참고하여 작성하였습니다.