Java 문제 풀이 - Wrapper

Wrapper 관련 주어진 문제 풀어보기


parseInt

문자열 str1, str2 두 수의 합 구하기

String str1 = "11";
String str2 = "22";
System.out.println(Integer.parseInt(str1) + Integer.parseInt(str2));

33


parseDouble

배열 arr 변수에 입력된 모든 실수형 숫자의 합 구하기

String[] arr = {"1.1", "2.2", "3.3"};
double sum = 0.0;

for (String s : arr) {
    sum += Double.parseDouble(s);
}
System.out.println(sum);

6.6


Boxing, UnBoxing

  • Wrapper 관련해 박싱과 언박싱 사용 예제
  • 문자열 str 변수를 Integer 객체 래퍼로 변환해서 출력하기
  • Integer 객체 래퍼를 기본형 int 변환해서 출력하기
  • 기본형 int 변수를 Integer 객체로 변환해서 출력하기
  • 오토박싱, 오토 언박싱이 발생되지 않아야한다.
String str = "9999";
        
Integer Tint = Integer.valueOf(str);
System.out.println("문자열 -> 객체래퍼 숫자로 변환: " + Tint);

int iint = Tint.intValue();
System.out.println("객체래퍼 -> 기본형 숫자로 변환: " + iint);

Integer Tint2 = Integer.valueOf(iint);
System.out.println("기본형 -> 객체래퍼 숫자로 변환: " + Tint2);

문자열 -> 객체래퍼 숫자로 변환: 9999
객체래퍼 -> 기본형 숫자로 변환: 9999
기본형 -> 객체래퍼 숫자로 변환: 9999


Auto Boxing, Auto UnBoxing

  • Wrapper 관련해 오토 박싱과 오토 언박싱 사용 예제
  • 문자열 str 변수를 Integer 객체 래퍼로 변환해서 출력하기
  • Integer 객체 래퍼를 기본형 int 변환해서 출력하기
  • 기본형 int 변수를 Integer 객체로 변환해서 출력하기
String str = "9999";

Integer Tint = Integer.valueOf(str);
System.out.println("문자열 -> 객체래퍼 숫자로 변환: " + Tint);

int iint = Tint;
System.out.println("객체래퍼 -> 기본형 숫자로 변환: " + iint);

Integer Tint2 = iint;
System.out.println("기본형 -> 객체래퍼 숫자로 변환: " + Tint2);

문자열 -> 객체래퍼 숫자로 변환: 9999
객체래퍼 -> 기본형 숫자로 변환: 9999
기본형 -> 객체래퍼 숫자로 변환: 9999