본문 바로가기
Programming Language/JAVA

문자열을 숫자로 (Integer) parseInt(String) VS valueOf(String)

by Ray 2022. 1. 17.

문자열 -> 숫자 변환??

Java를 사용하다보면, 우리는 문자열을 숫자로 변환시켜야 하는 상황을 자주 마주합니다.

그럼 어떻게 하시나요?

Java는 문자열->숫자 변환을 위해 2가지의 메소드를 제공하고 있습니다.

바로 Integer.valueOf 와 Integer.parseInt 입니다.

 String S = "123";

 int A = Integer.parseInt(S);
 Integer B = Integer.valueOf(S);

코드에서 본 것처럼, 언뜻 같은 기능을 하는 2개의 메소드의 차이를 알아보려고 합니다.

이미 힌트를 보여준 것 같지만, 좀 더 자세히 알아보겠습니다.


 

Integer.parseInt(String)

Java API 정의

public static int parseInt​(String s) throws NumberFormatException

Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.

Parameters:

s - a String containing the int representation to be parsed

Returns:

the integer value represented by the argument in decimal.

Throws:

NumberFormatException - if the string does not contain a parsable integer.


Java API 정의되어 있는 부분을 간단히 해석해보면,

  • 문자열 인수를 10진수 숫자로 분석해라.
  • 첫번째 문자로 주어지는 +와 -기호를 제외한 문자열의 문자들은 모두 숫자로 표현되야 한다.
  • parseInt(String, int) 메소드에 해당 문자열과 10이 인수로 주어진 것처럼 결과값 정수를 반환된다.  

 

Method Code

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

=> 문자열를 숫자로 변환하는데, parseInt(String, int)를 활용하네요

그럼 parseInt(String, int)도 찾아보겠습니다.

 

Integer.parseInt(String, int)

Java API 정의

public static int parseInt​(String s, int radix) throws NumberFormatException

Parses the string argument as a signed integer in the radix specified by the second argument. The characters in the string must all be digits of the specified radix (as determined by whether Character.digit(char, int) returns a nonnegative value), except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value. The resulting integer value is returned.

An exception of type NumberFormatException is thrown if any of the following situations occurs:

  • The first argument is null or is a string of length zero.
  • The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX.
  • Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign '-' ('\u002D') or plus sign '+' ('\u002B') provided that the string is longer than length 1.
  • The value represented by the string is not a value of type int.

Examples:

 parseInt("0", 10) returns 0
 parseInt("473", 10) returns 473
 parseInt("+42", 10) returns 42
 parseInt("-0", 10) returns 0
 parseInt("-FF", 16) returns -255
 parseInt("1100110", 2) returns 102
 parseInt("2147483647", 10) returns 2147483647
 parseInt("-2147483648", 10) returns -2147483648
 parseInt("2147483648", 10) throws a NumberFormatException
 parseInt("99", 8) throws a NumberFormatException
 parseInt("Kona", 10) throws a NumberFormatException
 parseInt("Kona", 27) returns 411787

 

Parameters:

s - the String containing the integer representation to be parsedradix - the radix to be used while parsing s.

Returns

:the integer represented by the string argument in the specified radix.

Throws

:NumberFormatException - if the String does not contain a parsable int.


간단히 해석해보면,

  • 문자열 인수를 주어진 기수에 맞는 숫자로 분석해라.
  • 첫번째 문자로 주어지는 +와 -기호를 제외한 문자열의 문자들은 기수에 맞는 숫자로 표현되어야 한다.
  • 결과값으로 정수가 반환된다.
  • 아래 상황이 발생하면, NumberFormatException의 예외가 던져진다.
    • 첫번째 인수(문자열)이 null이거나 길이가 0인 상황
    • 기수가 Character.MIN_RADIX보다 작거나 Character.MAX_RADIX보다 큰 상황
    • 첫번째 문자가 +/-인 경우를 제외하고, 문자열의 문자가 기수의 숫자가 아닌 상황
    • 문자열로 표현된 값이 int 형식의 값이 아닌 상황

 

Method Code

public static int parseInt(String s, int radix)
                throws NumberFormatException
    {
        /*
         * WARNING: This method may be invoked early during VM initialization
         * before IntegerCache is initialized. Care must be taken to not use
         * the valueOf method.
         */

        if (s == null) {
            throw new NumberFormatException("null");
        }

        if (radix < Character.MIN_RADIX) {
            throw new NumberFormatException("radix " + radix +
                                            " less than Character.MIN_RADIX");
        }

        if (radix > Character.MAX_RADIX) {
            throw new NumberFormatException("radix " + radix +
                                            " greater than Character.MAX_RADIX");
        }

        boolean negative = false;
        int i = 0, len = s.length();
        int limit = -Integer.MAX_VALUE;

        if (len > 0) {
            char firstChar = s.charAt(0);
            if (firstChar < '0') { // Possible leading "+" or "-"
                if (firstChar == '-') {
                    negative = true;
                    limit = Integer.MIN_VALUE;
                } else if (firstChar != '+') {
                    throw NumberFormatException.forInputString(s);
                }

                if (len == 1) { // Cannot have lone "+" or "-"
                    throw NumberFormatException.forInputString(s);
                }
                i++;
            }
            int multmin = limit / radix;
            int result = 0;
            while (i < len) {
                // Accumulating negatively avoids surprises near MAX_VALUE
                int digit = Character.digit(s.charAt(i++), radix);
                if (digit < 0 || result < multmin) {
                    throw NumberFormatException.forInputString(s);
                }
                result *= radix;
                if (result < limit + digit) {
                    throw NumberFormatException.forInputString(s);
                }
                result -= digit;
            }
            return negative ? result : -result;
        } else {
            throw NumberFormatException.forInputString(s);
        }
    }

code의 실행을 보면,

  1. 문자열 인수의 null 체크
  2. 기수 인수의 MIN_RADIX ~ MAX_RADIX 범위 체크
  3. 문자열 인수의 길이 체크와  음수/양수 체크
  4. 문자열 인수의 문자를 순회하면서, 기수에 맞는 숫자로 변환

 

 

즉, parseInt(String)은 parseInt(String, 10)을 불러와서 문자열을 숫자로 변환합니다.

문자열이 int 형식의 값으로 변환하지 못하는 경우에는 NumberFormatException을 발생시킵니다.

반환값은 10진수로 표현된 int 값입니다.

 

 

 

Integer.valueOf(String)

Java API 정의

public static Integer valueOf​(String s) throws NumberFormatException

Returns an Integer object holding the value of the specified String. The argument is interpreted as representing a signed decimal integer, exactly as if the argument were given to the parseInt(java.lang.String) method. The result is an Integer object that represents the integer value specified by the string.

In other words, this method returns an Integer object equal to the value of :  new Integer(Integer.parseInt(s))

 

Parameters:s - the string to be parsed.

Returns:an Integer object holding the value represented by the string argument.

Throws:NumberFormatException - if the string cannot be parsed as an integer.


 

간단히 해석해보면,

  • 해당 문자열의 값을 갖고있는 숫자 객체를 반환해라
  • 마치 parseInt(String, int)에 주어진 것처럼, 문자열 인수는 10진수로 표현된 정수로 해석된다.
  • 결과값은 해당 문자열의 값을 표현한 숫자 객체이다.
  • 즉, 해당 메소드는 new Integer(Integer.parseInt(s))와 동일한 값의 숫자 객체를 반환한다.
  • int 형식의 값으로 분석할 수 없는 경우, NumberFormatException를 던진다.

Method Code

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

=> 문자열를 숫자로 변환하는데, valueOf(String, int)를 활용하네요

그럼 valueOf(String, int)도 찾아보겠습니다.

 

 

Integer.valueOf(String, int)

Java API 정의

public static Integer valueOf​(String s, int radix) throws NumberFormatException

Returns an Integer object holding the value extracted from the specified String when parsed with the radix given by the second argument. The first argument is interpreted as representing a signed integer in the radix specified by the second argument, exactly as if the arguments were given to the parseInt(java.lang.String, int) method. The result is an Integer object that represents the integer value specified by the string.

In other words, this method returns an Integer object equal to the value of: new Integer(Integer.parseInt(s, radix))

 

Parameters:

  s - the string to be parsed.

  radix - the radix to be used in interpreting s

Returns:

  an Integer object holding the value represented by the string argument in the specifiedradix.

Throws:

 NumberFormatException - if the String does not contain a parsable int.


기수 부분이 설명이 추가된 것을 제외하면 동일합니다.

 

Method Code

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

 

 

즉, valueOf(String)은 valueOf(String, 10)을 불러와서 문자열을 숫자로 변환합니다.

그리고 valueOf(String, radix) 의 반환값은 new Integer(Integer.parseInt(s, radix)) 입니다.

문자열이 int 형식의 값으로 변환하지 못하는 경우에는 NumberFormatException을 발생시킵니다.

 

 

 


 

parseInt(String)  vs  valueOf(String) 

  Integer.parseInt(String s) Integer.valueOf(String s)
Method Integer.psrseInt(String s, 10) Integer.valueOf(String s, 10)
실제 동작 Integer.psrseInt(String s, 10) Integer.psrseInt(String s, 10)
Return int 값 Integer 객체

=>

결국 valueOf는 parseInt를 호출해서 문자열을 숫자값을 변환시킵니다.

그러나 paseInt로 변환한 숫자값을 그대로 반환하지 않고, Wrapper Class인 Integer 객체로 Boxing해서 반환합니다.

 

 

'Programming Language > JAVA' 카테고리의 다른 글

JVM (Java Virtual Machine ) 이란?  (0) 2022.01.17
왜 Java 11을 사용하나요?  (0) 2021.05.17