'자바를자바답게하는클래스[Wrapper Class]'에 해당되는 글 1건
- 2008.08.14 자바를자바답게하는클래스[Wrapper Class]
Wrapper Class
Wrapper 클래스란 기본 자료형을 객체로 만들어 주는 클래스들을 말한다.
Wrapper 클래스 설명 Boolean boolean을 객체로 취급하는 클래스 Byte byte를 객체로 취급하는 클래스 Character char를 객체로 취급하는 클래스 Short short를 객체로 취급하는 클래스 Integer int를 객체로 취급하는 클래스 Long long을 객체로 취급하는 클래스 Float float을 객체로 취급하는 클래스 Double double을 객체로 취급하는 클래스
Wapper 클래스는 비슷한 멤버를 가지므로 Interger 클래스의 멤버만 살펴보고 나머지 클래스들은 API를 참고하자.
☞ Integer 클래스의 유용한 생성자
public Integer(int value)
정수 value를 값(this.value)으로 가지는 객체를 만든다.
public Integer(String s) throws NumberFormatException
숫자로 구성된 문자열 s를 값으로 가지는 객체를 만든다. s가 숫자로 구성된 문자열이 아니면 NumberFormatException을 던진다.
예외가 발생하는
예) "12p", "abc"
옳은 예) "123", "-123"
NumberFormatException은 문자열을 숫자로 변환할 때 문자열이 숫자나 부호로 구성되어 있지 않으면 발생한다. 이놈은 RuntimeException의 자식이므로 예외 처리를 하지 않아도 된다.
##Wrapper1.java##
public class Wrapper1{
public static void main(String[] args){
int a=7;
String b="123";
Integer w1=new Integer(a); // 7을 가지는 Integer 객체가 생김
Integer w2=new Integer(b); // 숫자 123을 가지는 Integer 객체가 생김
System.out.println(w1); // 7
System.out.println(w2); // 123
}
}
☞ Integer 클래스의 유용한 메소드
public byte byteValue(), int intValue(), short shortValue() ,
long longValue(), float floatValue(), double doubleValue()
해당 자료형으로 형 변환한 값을 반환한다.
public static int parseInt(String s) throws NumberFormatException
문자열 s를 10진수 정수형(int)으로 변환한 값을 반환한다
public static int parseInt(String s, int radix) throws NumberFormatException
문자열 s를 radix진수 정수형으로 변환한 값을 반환한다.
public static String toBinaryString(int i)
i를 2진수로 변환하여 String 객체로 반환한다.
public static String toHexString(int i)
i를 16진수로 변환하여 String 객체로 반환한다.
public static String toOctalString(int i)
i를 8진수로 변환하여 String 객체로 반환한다.
public static String toString(int i)
i를 10진수로 변환하여 String 객체로 반환한다.
##Wapper2.java##
public class Wrapper2{
public static void main(String[] args){
int a=20;
Integer w=new Integer(10);
System.out.println(a+w.intValue()); // 30
int b=Integer.parseInt("123");
System.out.println(b); // 123
int c=Integer.parseInt("12",8); // 8진수 12
System.out.println(c); // 10, println()은 10진수로 출력한다.
// 11111111111111111111111111111111
System.out.println(Integer.toBinaryString(-1));
}
}
##혼자 해보기##
어떤 문자열이 숫자로 이루어진 문자열인지 아닌지를 알아보는 메소드 isNumberic을 만들어보자.
public class Alone12_3{
static boolean inNumberic(String num){
// 여기에 코드 삽입
}
public static void main(String[] args){
System.out.println(isNumberic("123"));
System.out.println(isNumberic("-123.45"));
System.out.println(isNumberic("0x12"));
System.out.println(isNumberic("1abc"));
System.out.println(isNumberic("-1a33"));
}
}
##출력 결과 예시##
true
true
true
false
false
'My work space > Java' 카테고리의 다른 글
scjp(내용정리)_수정판.hwp (0) | 2008.08.14 |
---|---|
자바를 자바답게 하는클래스[Collection] (0) | 2008.08.14 |
자바를자바답게하는클래스[StringTokenizer클래스] (0) | 2008.08.14 |
자바를자바답게하는클래스[StringBuffer클래스] (0) | 2008.08.14 |
[아시나요?]equals 와 == (0) | 2008.08.14 |