공부했던 자료 정리하는 용도입니다.

재배포, 수정하지 마세요.

 

 

 

 

래퍼 클래스(Wrapper Class)

  기본형(primitive type) 변수를 객체로 다루기 위해서 사용하는 클래스이다.  char 형과  int 형을 제외한 나머지는 자료형 이름의 첫 글자를 대문자로 한 것이 각 래퍼 클래스의 이름이다. 래퍼 클래스의 생성자는 매개변수로 문자열이나 각 자료형들의 값들을 인자로 받는다. 이때 주의해야 할 것은 생성자의 매개변수로 문자열을 제공할 때, 각 자료형에 알맞은 문자열을 사용해야 한다는 것이다. 예를 들어  new Integer("1.0") 을 해버리면  NumberFormatException 이 발생한다. 

 

 

 

 

래퍼(Wrapper) 클래스의 생성자

Primitive Type(기본형) Wrapper class(래퍼 클래스) Constructor(생성자)
boolean Boolean Boolean(boolean value)
Boolean(String s)
char Character Character(char value)
byte Byte Byte(byte value)
Byte(String s)
short Short Short(short value)
Short(String s)
int Integer Integer(int value)
Integer(String s)
long Long Long(long value)
Long(String s)
float Float Float(double value)
Float(float value)
Float(String s)
double Double Double(double value)
Double(String s)

 

 

package Example;

public class Example {
	public static void main(String[] args) {
		Integer i1 = new Integer(100);
		Integer i2 = new Integer(100);
		
		System.out.println("i1 == i2 ? " + (i1 == i2));
		System.out.println("i.equals(i2) ? " + i1.equals(i2));
		System.out.println("i.compareTo(i2) ? " + i1.compareTo(i2));
		System.out.println("i.toString()? " + i1.toString());
		
		System.out.println();
		
		System.out.println("MAX_VALUE = " + i1.MAX_VALUE);
		System.out.println("MIN_VALUE = " + i1.MIN_VALUE);
		System.out.println("SIZE = " + Integer.SIZE + " bits");
		System.out.println("BYTES = " + Integer.BYTES + " bytes");
		System.out.println("TYPE = " + Integer.TYPE);
	}
}

 

실행결과

래퍼 클래스는 모두  equals( ) 가 오버라이딩 되어 있어서 주소 값이 아닌 객체의 값을 비교한다. 하지만 오토 박싱이 된다고 해도  Integer 객체에 비교 연산자를 사용할 수는 없기 때문에 비교 연산자 대신  compareTo( ) 를 사용해야 한다. 또한  toString( ) 도 오버라이딩 되어 있어서 객체가 가지고 있는 값을 문자열로 변환하여 반환할 수 있다. 이 외에도 래퍼 클래스는  MAX_VALUE  MIN_VALUE  SIZE  BYTES (JDK 1.8부터),  TYPE 등의  static 상수를 공통적으로 갖고 있다.

 

 

 

 

Number 클래스

래퍼클래스의 상속계층도

 Number 클래스는 추상 클래스로 내부적으로 숫자를 멤버 변수로 갖는 래퍼 클래스들의 조상이다. 위의 그림에서 알 수 있듯이 기본형 중에서도 숫자와 관련된 래퍼 클래스들은 모두  Number 클래스의 자식이라는 것을 알 수 있다.  BigInteger 는  long 으로도 다룰 수 없는 큰 범위의 정수,  BigDecimal 은  double 로도 다룰 수 없는 큰 범위의 부동소수점 수를 처리하기 위한 것으로 연산자의 역할을 대신하는 다양한 메서드가 있다.

 

 

 

 

문자열 → 숫자 변환

문자열 → Primitive Type(기본형) 문자열 → Wrapper class(래퍼 클래스)
 반환값이 기본형 
byte    b = Byte.parseByte("100");

short    s = Short.parseShort("100");
int    i = Integer.parseInt("100");
long    l = Long.parseLong("100");
float    f = Float.parseFloat("3.14");
double    d = Double.parseDouble("3.14");
 반환값이 래퍼클래스 타입 
Byte    b = Byte.valueOf("100");

Short    s = Short.valueOf("100");
Integer    i = Integer.valueOf("100");
Long    l = Long.valueOf("100");
Float    f = Float.valueOf("3.14");
Double    d = Double.valueOf("3.14");

JDK 1.5부터 도입된  오토 박싱(autoboxing)  기능 때문에 반환 값이 기본형일 때와 래퍼 클래스일 때의 차이가 없어졌다. 그래서 구별 없이  valueOf( ) 를 써도 상관은 없다. 성능은  valueOf( ) 가 조금 더 느리다. 

 

 

static int parseInt(String s, int radix)	// 문자열 s를 radix진법으로 인식
static Intever valueOf(String s, int radix)

//아래의 예제처럼 사용가능하다
int i1 = Integer.parseInt("100", 2);	// 100(2) == 4
int i2 = Integer.parseInt("100", 8);	// 100(8) == 64
int i3 = Integer.parseInt("100", 16)	// 100(16) == 256
int i4 = Integer.parseInt("FF", 16)	// FF(16) == 255
int i5 = Integer.parseInt("FF");	//진법을 생략하면 10진수로 간주해서 NumberFormatException 발생

문자열이  10 진수가 아닌 다른 진법(radix)의 숫자일 때도 변환이 가능하다. 진법을 생략하면  10 진수로 간주하기 때문에  NumberFormatException 이 발생할 수도 있어 주의해야 한다.

 

 

 

 

오토 박싱(Autoboxing) & 언박싱(Unboxing)

컴파일 전의 코드 컴파일 후의 코드
int i = 5;
Integer iObj = new Integer(7);

int sum = i + iObj;
int i = 5;
Integer iObj = new Integer(7);

int sum = i + iObj.intValue( );

과거(JDK 1.5 이전)에는 기본형과 참조형간의 연산이 불가능해서, 연산하려면 기본형을 래퍼 클래스의 객체로 만들어서 연산해야 했다. 그러나 이제는 컴파일러가 자동으로 변환하는 코드를 넣어주기 때문에 따로 형변환을 하지 않아도 된다.  기본형 값을 래퍼 클래스의 객체로 자동 변환해주는 것을  오토박싱(autoboxing) 이라고 하고, 반대의 과정을  언박싱(unboxing) 이라고 한다. 예를 들어 내부적으로 객체 배열을 가지고 있는  Vector 클래스나  ArrayList 클래스에 기본형 값을 저장해야 할 때나 형변환이 필요할 때 컴파일러가 자동적으로 코드를 추가해준다. 

 

 

package Example;

public class Example {
	public static void main(String[] args) {
		int i = 10;
		
		//기본형 -> 참조형변환(생략가능)
		Integer intg = (Integer)i;	// Integer intx = Integer.valueOf(i);
		Object obj = (Object)i;	// Object obj = (Object)Integer.valueOf(i);
		
		Long lng = 100L;	//Long lng = new Long(100L);
		
		int i2 = intg + 10;	// 참조형과 기본형간의 연산 가능
		long l = intg + lng;	//참조형간 덧셈도 가능
		
		Integer intg2 = new Integer(20);
		int i3 = (int)intg2;	//참조형 -> 기본형변환(생략가능)
		
		Integer intg3 = intg2 + i3;
		
		System.out.println("i = " + i);
		System.out.println("intg = " + intg);
		System.out.println("obj = " + obj);
		System.out.println("lng = " + lng);
		System.out.println("intg  + 10 = " + i2);
		System.out.println("intg + lng = " + l);
		System.out.println("intg2 = " + intg2);
		System.out.println("i3 = " + i3);
		System.out.println("intg2 + i3 = " + intg3);
	}
}

오토 박싱과 언박싱을 확인하는 예제이다. 컴파일러가 자동으로 오토 박싱과 언박싱을 해주는 덕분에 기본형과 참조형간의 형변환이 가능하고 참조형간의 연산도 가능하다. 

 

 

 

+ Recent posts