Java 래퍼 - 기본으로 제공되는 래퍼 클래스

흔히 사용하는 래퍼 클래스는 자바에서 기본으로 제공하는 클래스가 있다.

자바의 기본형에 대응하는 래퍼 클래스를 살펴보자

  • Byte(byte)
  • Short(short)
  • Integer(int)
  • Long(long)
  • Float(float)
  • Double(double)
  • Character(char)
  • Boolean(bool)

그리고 자바 래퍼 클래스의 값들은 같은 특징이 있다.

  • 불변 객체
  • equals 동등성으로 비교해야한다.
public class Main {
    public static void main(String[] args) {
        Integer Vint = new Integer(100);
        Integer Vint2 = Integer.valueOf(200); // -128 ~ 127 자주 사용하는 값 재사용, 불변 
        System.out.println("Value Integer = " + Vint);
        System.out.println("Value Integer = " + Vint2);
    }
}

100
200

객체 사용하듯이 사용해도 된다.
다만 new Integer(100) 코드는 IDE에서 빨강 밑줄이 발생할 수 있는데, 클래스 내부에서 Deprecated 처리로 앞으로 없어질 수 있다는 뜻이다. 주석에는 valueOf 대신 사용하라고 안내하고 있다.

값 출력은 Vint -> Vint.toString() 오버라이딩 되어 반환하고 있다.


래퍼 클래스 사용 예시

Integer Vint = Integer.valueOf(100);
Integer Viint = Integer.valueOf(100);
System.out.println("Value Integer = " + Vint);

Value Integer = 100


Long Vlong = Long.valueOf(100);
System.out.println("Value Long = " + Vlong);

Value Long = 100


Double Vdouble = Double.valueOf(100);
System.out.println("Value Double = " + Vdouble);

Value Double = 100.0


System.out.println("래퍼 클래스 내부 값 읽기");
Integer Vint = Integer.valueOf(100);
int iint = Vint.intValue(); // int형으로 반환
System.out.println(iint);

래퍼 클래스 내부 값 읽기
100


System.out.println("래퍼 클래스 내부 값 읽기");
Long Vlong = Long.valueOf(100);
long llong = Vlong.longValue();
System.out.println(llong);

래퍼 클래스 내부 값 읽기
100


System.out.println("래퍼 클래스 내부 값 읽기");
Double Vdouble = Double.valueOf(100);
double ddouble = Vdouble.doubleValue();
System.out.println(ddouble);


래퍼 클래스 내부 값 읽기
100.0


System.out.println("래퍼 클래스 비교");
Integer Vint = Integer.valueOf(100);
Integer Viint = Integer.valueOf(200);
System.out.println("동일성 == ? " + (Vint == Viint));


래퍼 클래스 비교
동일성 == ? true


System.out.println("래퍼 클래스 비교");
Integer Vint = Integer.valueOf(100);
Integer Viint = Integer.valueOf(200);
System.out.println("동등성 ? " + (Vint.equals(Viint)));

래퍼 클래스 비교
동등성 ? false