티스토리 뷰

java

[JAVA] autoboxing과 unboxing

jjuniyo 2023. 5. 31. 15:25

자바 컴파일러가 서로 상응하는 primitive type과 wrapper class 끼리 자동 변환해주는데, 이것을 각각 autoboxing과 unboxing 이라고 부른다.
autoboxing과 unboxing에 용어에 대해서 하나씩 알아보자.

autoboxing

  • primitive value 를 상응하는 wrapper class의 객체로 변환하는 것
  • Ex) int -> Integer, double -> Double

autoboxing 하는 경우

  • 호출할 때 primitive value를 전달하지만, method의 parameter가 wrapper class 객체 일 경우
    public static void main(String[] args) { 
        doSomeThing(0); 
    } 
    private static void doSomeThing(Integer i) {
        ... 
    }
  • 상응하는 wrapper class의 값으로 할당되는 경우 (Ex. 연산)
    List<Integer> li = new ArrayList<>();
    for (int i = 1; i < 50; i += 2) 
        li.add(i); // 실제 동작할 때 li.add(Integer.valueOf(i));

unboxing

  • wrapper class의 객체를 상응하는 primitive value로 변환하는 것
  • Ex) Integer -> int, Double -> double

unboxing 하는 경우

  • 호출할 때 wrapper class object를 전달하지만, method의 parameter가 primitive type일 경우
    public static void main(String[] args) {
        doSomeThing(new Integer(0));
    }
    private static void doSomeThing(int i) {
        ... 
    }
  • 상응하는 primitive type으로 할당되는 경우 (Ex. 연산)
    public static int sumEven(List<Integer> li) {
    int sum = 0;
    for (Integer i: li) 
        if (i % 2 == 0) // 실제 동작할 때 if(i.intValue() % 2 == 0) 
            sum += i; // sum += i.intValue();
    return sum; 
    }

마지막으로 stackoverflow에서 처음으로 알게된 것이 있어서 소개해보겠다.

public static void main(String[] args) {
    System.out.println(doSomeThing());
}

public static int doSomeThing() {
    return true ? null : 0; // NPE
}

public static int doSomeThing2() {
    if(true) return (Integer) null; // NPE
    return 0;
}

public static int doSomeThing3() {
    if(true) return null; // compile error
    return 0;
}

doSomeThing()은 null과 0을 Integer로 autoboxing 한 후 return 할 때 unboxing(Integer.intValue())이 된다.
아래 문서에서는 3항 연산자를 사용했을 때 반환하는 결과(? A : B) 타입 두 개에 대하여 조건 표현식 타입이 결정된다고 기술되어 있다. doSomeThing() null:0의 조합으로 Integer타입이 결정되어 컴파일 에러가 발생하지 않았으며 runtime에서는 null : 0이 각각 autoboxing 한 후 결과 값을 반환할 때 unboxing 이 일어난다는 것이다.
https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25

 

doSomeThing2()는 (Integer) null 리턴할 때 unboxing이 일어난다.
언뜻보면 doSomeThing3()는 primitive type이 아닌 null을 반환하여 컴파일 에러가 발생한다.

 

 

출처

https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25

https://stackoverflow.com/questions/53997710/returning-null-as-primitive-type-in-java-works-why https://stackoverflow.com/questions/8098953/returning-null-as-an-int-permitted-with-ternary-operator-but-not-if-statement

'java' 카테고리의 다른 글

[JAVA] call by value  (0) 2023.06.01
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함