• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    해결됨

래퍼 클래스 - 참조형 기본형 비교

24.05.03 19:04 작성 조회수 65

0

public class WrapperClassMain {
    public static void main(String[] args) {
        Integer i = new Integer(10);
        Integer in = new Integer(10);
        Integer integerObj = Integer.valueOf(10);  //-128~ 127 자주 사용하는 숫자 값 재사용
    

        System.out.println("내부 값 읽기");
        int intValue = i.intValue();
        System.out.println(intValue);

        System.out.println(i == intValue); //true
        System.out.println(i == integerObj); //false
        System.out.println(i == in); //false
        System.out.println(in == intValue); //true

    }
}

래퍼 클래스는 인스턴스의 참조값을 비교한다고 했는데, (i==intValue) 이 부분에서 참조형과 기본형을 비교하는 부분에서는 왜 true가 나오나요?

답변 1

답변을 작성해보세요.

0

David님의 프로필

David

2024.05.04

안녕하세요. 주형님, 공식 서포터즈 David입니다.

자바는 다음과 같은 상황에서 intValue를 언박싱하여 비교합니다. (참고)

i == intValue

감사합니다.

주형님의 프로필

주형

질문자

2024.05.07

inValue는 언박싱이 이미 된 것 아닌가요?? 혹시 i를 언박싱해서 비교한다는 말씀이신가요?

David님의 프로필

David

2024.05.07

네, 제가 잘못 기재했습니다.

i가 언박싱됩니다.