반응형
래퍼 클래스(Wrapper Class)란?
메소드의 argument(전달인자)로 객체타입만 요구될때 기본 타입의 데이터를 객체로 변환한 후 작업을 수행해야 합니다.
이때 기본타입(Primitive Type)을 객체로 변환할때 사용하는 클래스들을 래퍼 클래스(Wrapper Class)라고 합니다.
래퍼클래스는 java.lang패키지에 포함되어 제공합니다.
래퍼 클래스의 종류
기본타입(Primitive Type) | 래퍼클래스 (Wrapper Class) |
boolean | Boolean |
char | Character |
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
박싱(Boxing)과 언박싱(UnBoxing)
래퍼 클래스는 산술 연산을 위한 클래스가 아닌 인스턴스에 저장된 값만을 참조할 수 있기때문에 저장된 값을 변경할 수 없습니다.
아래의 이미지와 같이 기본타입을 래퍼 클래스로 변환하는 과정을 박싱(Boxing),
래퍼 클래스를 기본타입으로 변환하는 과정을 언박싱(UnBoxing)이라고 합니다.
JDK 1.5부터는 박싱과 언박싱이 필요한 상황에서 자바 컴파일러가 자동으로 처리해 줍니다.
자동화된 박싱과 언박싱을 오토 박싱(AutoBoxing)과 오토 언박싱(AutoUnBoxing)이라고 부릅니다.
래퍼클래스의 비교연산
오토언박싱을 통해 >, <, >=, <= 같은 비교연산은 가능하지만 같은값인지 확인하는 동등 연산자(==)의 경우 클래스 객체이기 때문에 두 인스턴스의 주소값을 비교합니다.
따라서 저장된 값의 동등여부를 판단 하려면 equals() 메소드를 사용해야 합니다.
예제
// Boxing
Integer integerNum = new Integer(3); // integerNum.getClass() 결과: class java.lang.Integer
Character character = new Character('A'); // character.getClass() 결과: class java.lang.Character
// UnBoxing
int intNum = integerNum.intValue(); // int
char char1 = character.charValue(); // char
int result = integerNum + integerNum;
// AutoBoxing
Integer integerNum = 3; // integerNum.getClass() 결과: class java.lang.Integer
Character character = 'A'; // character.getClass() 결과: class java.lang.Character
// AutoUnBoxing
int intNum = integerNum; // int
char char1 = character; // char
Integer result = intNum + intNum;
// 래퍼클래스 비교연산
Integer integerNum = new Integer(3);
Integer integerNum2 = new Integer(3);
Integer integerNum3 = new Integer(1);
System.out.println(integerNum > integerNum3); // true
System.out.println(integerNum < integerNum3); // false
System.out.println(integerNum >= integerNum2); // true
System.out.println(integerNum <= integerNum2); // true
System.out.println(integerNum == integerNum2); // false
System.out.println(integerNum.equals(integerNum2)); // true
반응형
'프로그래밍 언어&프레임워크 > java' 카테고리의 다른 글
[Java/자바] 컬렉션 프레임워크 (0) | 2021.09.13 |
---|---|
[Java/자바] 제네릭 프로그래밍 (0) | 2021.09.13 |
[Java/자바] 배열과 ArrayList (0) | 2021.08.23 |
[Java/자바] MVC 패턴(Model, View, Controller) (0) | 2021.08.07 |
[Java/자바] 자료형(DataType) (0) | 2021.08.04 |