본문 바로가기

프로그래밍언어/Java

[Java 중급] 자바 래퍼 클래스

자바 래퍼 클래스


자바는 기본형에 대응하는 래퍼 클래스를 기본으로 제공한다. 

  • byte -> Byte
  • short -> Short
  • int -> Integer
  • long -> Long
  • float -> Float
  • double -> Double
  • char -> Character
  • boolean -> Boolean

=> 자바가 제공하는 기본 래퍼클래스는 두 가지 특징을 가진다. 

1. 불변이다. 

2. equals로 비교해야 한다. 

 

예제


 

 

package lang.wrapper;

public class WrapperClassMain {

    public static void main(String[] args) {
        Integer newInteger = new Integer(10); // 삭제 예정, 대신 valueOf 사용 권장
        Integer integerObj = Integer.valueOf(10);
        Long longObj = Long.valueOf(100);
        Double doubleObj = Double.valueOf(10.5);

        System.out.println("newInteger = " + newInteger);
        System.out.println("integerObj = " + integerObj);
        System.out.println("longObj = " + longObj);
        System.out.println("doubleObj = " + doubleObj);
        
        System.out.println("내부 값 읽기");
        int intValue = integerObj.intValue();
        System.out.println("intVlaue = " + intValue);
        long longValue = longObj.longValue();
        System.out.println("longValue = " + longValue);

        System.out.println("비교");
        System.out.println("==: " + (newInteger == integerObj));
        System.out.println("equals:" + (newInteger.equals(integerObj)));
        
        
        

    }
}

 

=>

래퍼 클래스 생성 - 박싱(Boxing)

  • 기본형을 래퍼 클래스로 변경하는 것을 마치 박스에 물건을 넣은 것 같다고 해서 박싱(Boxing)이라 한다. 

intValue() - 언박싱(Unboxing)

  • 래퍼 클래스에 들어있는 기본형 값을 다시 꺼내는 메서드이다. 
  • 박스에 들어있는 물건을 꺼내는 것 같다고 해서 언박싱(UnBoxing)이라 한다. 

 

 

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