기록하는 코더

[JAVA] parseInt와 ValueOf의 차이점 본문

JAVA

[JAVA] parseInt와 ValueOf의 차이점

damda_di 2023. 1. 15. 00:29

자바로 코드를 짜다보면 문자형으로 입력된 값을 숫자형으로 변형시켜주는 경우가 많다.

이 때 쓰는 메소드로 parseIntValueOf가 있다.

// 사용 예시

int a = Integer.parseInt("10");
int b = Integer.ValueOf("10");

System.out.print("a = " + a);
System.out.print("b = " + b);

//출력결과
// a = 10
// b = 10

 

 

parseInt의 리턴타입은 자료형 ( 원시데이터 int 타입을 반환 )

    /**
     * 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 {@code '-'}
     * ({@code '\u005Cu002D'}) to indicate a negative value or an
     * ASCII plus sign {@code '+'} ({@code '\u005Cu002B'}) 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 {@link #parseInt(java.lang.String,
     * int)} method.
     *
     * @param s    a {@code String} containing the {@code int}
     *             representation to be parsed
     * @return     the integer value represented by the argument in decimal.
     * @throws     NumberFormatException  if the string does not contain a
     *               parsable integer.
     */
    public static int parseInt(String s) throws NumberFormatException {
        return parseInt(s,10);
    }

 

 

valueOf의 리턴타입은 객체 ( Integer 래퍼(wrapper)객체를 반환 )

  • Integer 타입은 기본형 타입(Primitive Type)인 int형의 박싱(boxing)한 결과이다.
  • int형을 객체로 쓰기위한 객체이며, 래퍼 클래스로 감싸고 있는 기본형 타입의 값이라고 볼 수 있다.

 

java.lang.Integer에 정의된 valueOf 설명을 보면 

    /**
     * Returns an {@code Integer} object holding the
     * value of the specified {@code String}. The argument is
     * interpreted as representing a signed decimal integer, exactly
     * as if the argument were given to the {@link
     * #parseInt(java.lang.String)} method. The result is an
     * {@code Integer} object that represents the integer value
     * specified by the string.
     *
     * <p>In other words, this method returns an {@code Integer}
     * object equal to the value of:
     *
     * <blockquote>
     *  {@code new Integer(Integer.parseInt(s))}
     * </blockquote>
     *
     * @param      s   the string to be parsed.
     * @return     an {@code Integer} object holding the value
     *             represented by the string argument.
     * @throws     NumberFormatException  if the string cannot be parsed
     *             as an integer.
     */
    public static Integer valueOf(String s) throws NumberFormatException {
        return Integer.valueOf(parseInt(s, 10));
    }

 

     *  {@code new Integer(Integer.parseInt(s))}

ValueOf는 메소드 내부적으로 parseInt를 다시 호출하는 것을 볼 수 있다.

 

 

ParseInt와 ValueOf의 차이점

  • parseInt를 사용하여 변형한 숫자는 원시 타입 변수(int 타입)이므로 연산이 가능하고
  • Integer.valueOf를 이용한 숫자는 wrapper 객체 타입이므로  연산이 불가능하다.

 

참고링크 :