본문 바로가기
Java

[Java] pasreInt와 valueOf의 차이점 / 문자열을 정수로 변환하기

by 가영리 2022. 6. 6.
728x90

https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV5QPRjqA10DFAUq&categoryId=AV5QPRjqA10DFAUq&categoryType=CODE&problemTitle=2058&orderBy=FIRST_REG_DATETIME&selectCodeLang=ALL&select-1=&pageSize=10&pageIndex=1&&&&&&&&&

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

 

 

문제 설명

 

하나의 자연수를 입력 받아 각 자릿수의 합을 계산하는 프로그램을 작성하라.

 

제약 사항

 

자연수 N은 1부터 9999까지의 자연수이다.

 

입력

 

입력으로 자연수 N이 주어진다.

 

출력

 

각 자릿수의 합을 출력한다.

 

입출력 예시

 

input output
123 6

 

풀이

 

public class Problem2058{
	public static void main(String[] args){
    	
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        int sum = 0;
        
        for(int i=0; i<str.length(); i++)
        {
        	sum += Integer.parseInt(str.subString(i,i+1));
            //sum += Integer.valueOf(str.subString(i, i+1));
        }
        
        System.out.println(sum);
   	}
}

 

 

이 문제를 풀면서 "10"와 같은 문자열을 숫자로 바꾸는 방법을 찾아보다가 두 가지 방법이 있다는 것을 알게 되었다.

 

- Integer.parseInt() 

 

public static int parseInt(String s) throws NumberFormatException {
        return parseInt(s,10);
}

 

parseInt()는 기본 자료형인(primitive type) int형을 반환한다.

 

 

- Integer.valueOf()

 

public static Integer valueOf(String s, int radix) throws NumberFormatException{
	return Integer.valueOf(parseInt(s, radix));
}

 

valueOf()는  Integer wrapper 객체(Object)를 반환한다.

 

 

Int와 Integer은 뭐가 다를까?

 

- int

  • primitive 자료형
  • 산술 연산이 가능하다.
  • null로 초기화 할 수 없다.

 

- Integer

  • Wrapper 클래스(객체)
  • Unboxing을 하지 않으면 산술 연산이 불가능 하지만, null 값을 처리할 수 있다.
  • null로 초기화 할 수 있다.
  • null 값 처리가 용이해 SQL과 연동할 경우 처리가 용이하다.

 

여기서 Unboxing이란 Integer를 int로 변환시키는 것을 말한다.

 

 

Integer는 참조자료형 또는 기본자료형들에 대응되는 객체화된 자료형(boxed primitive type)이라고 한다.

 

int a = 1;
int b = 1;
 
Integer c = new Integer(2);
Integer d = new Integer(2);
 
if(a==b) System.out.println("same");
 
if(c==d) System.out.println("same");
else System.out.println("different");

if(c.equals(d)) System.out.println("same");
else System.out.println("different");

 

java11에서는 Integer 객체를 생성했을 때  "The constructor Integer(int) is deprecated since version 9"라는 warning이 뜨긴 하지만 실행은 된다.

 

실행 결과

 

 

 

결과 분석

 

1. a == b -> true  : 기본자료형인 int는 저장된 값을 비교하기 때문에 true

2. c == b -> false : 객체화된 자료형 Integer는 객체의 주소값을 비교하기 때문에 false

3. c.equals(b) -> true : equals는 저장된 값을 비교하기 때문에 true