728x90
ch9 - 25 ~ 27
래퍼 클래스, Number 클래스
ch9 - 25
래퍼 (wrapper) 클래스
기본형 (원시타입) 을 감싸는 클래스를 의미.
- 8개의 기본형을 객체로 다뤄야 할 때 사용 하면 된다.
public final class Integer extends Number implements Comparable {
..
private int value; // 기본형 (int) 을 감싸고 있다.
..
}
대부분은, 기본형 이름에 소문자를 대문자로 바꾸면 래퍼 클래스 이다.
boolean -> Boolean
char -> Character
byte -> Byte
short -> Short
int -> Integer
long -> Long
float -> Float
double -> Double
[ 참고 ]
Java 언어의 90%는 객체 지향 언어 이다.
하지만, 모든게 객체는 아니다.
"기본형" 이 있기 때문인데, 성능 때문에 그렇다.
int i = 10;
변수 i를 사용 해서, 정수 10을 변수 i에 바로 저장 하면 끝이다.
>> 직접 접근이 가능 하다.
Integer i2 = new Integer("100");
참조변수 i2는 주소값을 가지게 되고,
참조변수가 가리키는 주소값을 가서 정수 100을 접근 해야 한다.
참조형은 참조변수를 통해서만 데이터 접근이 가능 하기 때문에, 직접 접근이 안된다.
ch9 - 26
래퍼 (wrapper) 클래스 예제
import static java.lang.System.out;
class Ex9_14 {
public static void main(String[] args) {
Integer i = new Integer(100);
Integer i2 = new Integer(100);
out.println("i==i2 ? " + (i == i2));
out.println("i.equals(i2) ? " + i.equals(i2));
out.println("i.compareTo(i2) = " + i.compareTo(i2)); // 같으면 0 반환, 작으면 양수 반환, 크면 음수 반환.
out.println("i.toString() = " + i.toString());
out.println("MAX_VALUE = " + Integer.MAX_VALUE); // +21 억
out.println("MIN_VALUE = " + Integer.MIN_VALUE); // -21 억
out.println("SIZE = " + Integer.SIZE + " bits"); // 32 비트.
out.println("BYTES = " + Integer.BYTES + " bytes"); // 4 바이트.
out.println("TYPE = " + Integer.TYPE); // int
// Integer을 예시로 들었지만,
// 그 외에 모든 래퍼 클래스들 모두의 타입 정보들을 확인 할 수 있다.
}
}
[ console ]
ch9 - 27
Number 클래스
- 모든 숫자 래퍼 클래스의 조상 이다.
Object 밑에,
Boolean, Character, Number 가 있다.
이 Number 클래스 하위에,
Byte, Short, Integer, Long, Float, Double, BigInteger, BigDecimal 이 있다.
BigInteger 은 아주 큰 정수를 의미 하고,
BigDecimal 은 아주 큰 실수를 의미 한다.
암튼, Number 클래스는 모든 숫자의 조상 클래스 이다.
public abstract class Number implements java.io.Serializable { // 추상 클래스 이다.
public abstract int intValue();
public abstract long longValue();
public abstract float floatValue();
public abstract double doubleValue();
public byte byteValue() {
return (byte) intValue();
}
public short shortValue() {
retrun (short) intValue();
}
}
래퍼 객체를 기본형 값으로 바꿔주는 메서드 들을 가지고 있다.
new Integer(100) 이 있다고 할 때,
intValue() 메서드를 사용 하면,
int 100 으로 바꿔 준다.
반응형
'Java의 정석 > java.lang 패키지 & 유용한 클래스' 카테고리의 다른 글
문자열과 숫자 변환, 오토박싱 & 언박싱 (0) | 2023.09.02 |
---|---|
StringBuilder, Math 클래스 (0) | 2023.09.02 |
StringBuffer 클래스의 메서드 (0) | 2023.09.02 |
StringBuffer 클래스 (문자열 저장 & 다루기) (0) | 2023.09.01 |
StringJoiner, 문자열과 기본형 변환 (0) | 2023.09.01 |