본문 바로가기
카테고리 없음

[Java] valuOf()와 parseInt() 차이

by 왕 달팽이 2020. 9. 4.
반응형

자바 코딩을 하다보면 문자열 형태로 표현된 정수를 정수 타입 값으로 변환해야할 경우가 있습니다. 이 경우 vlueOf() 메서드와 parseInt() 메서드를 사용하게 됩니다.

int number1 = Integer.valueOf("100");
System.out.println("number1 = " + number1);

int number2 = Integer.parseInt("100");
System.out.println("number2 = " + number2);

"100"이라는 문자열을 정수형 값으로 변경하는 방법은 위 코드에서 본 것처럼 Integer.valueOf() 메서드와 Integer.parseInt() 메서드가 있습니다. 이 프로그램을 실행시키면 다음과 같이 동일한 결과를 얻을 수 있습니다.

number1 = 100
number2 = 100

결과는 같아 보이지만 Integer.parseInt()와 Integer.valueOf()는 약간 다른 점이 있습니다.

Integer.parseInt()

parseInt() 메서드의 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.

parseInt() 메서드는 결과값을 항상 int 형으로 리턴합니다. 이 때 반환되는 반호나되는 값은 객체가 아닌 기본 자료형(Primitive Type)입니다.

Integer.valueOf()

valueOf() 메서드의 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.

문자열의 값을 정수형으로 변환한 다음 Integer 객체로 만들어서 반환합니다. 즉 new Integer(Integer.parseInt(s)) 값이 리턴됩니다.

사실 Java 1.5에서 도입된 'Autoboxing and Unboxing' 덕에 서로 뭘써도 상관이 없습니다. Integer 객체로 리턴을 받아서 int 변수에 할당하면 자동으로 형변환이 일어나기 때문입니다. 대신 내부적으로 객체 생성 오버헤드가 있을 수 있습니다.

 

반응형

댓글