JAVA

[Java] Integer.valueif 와 parseInt의 차이점

로춘남 2022. 4. 15. 15:40
728x90


자바를 사용하다보면 문자열 형태로 표현된 정수를 정수 타입 값으로 변환해야할 경우가 있다. 이 경우 valueOf() 메서드와 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 Umboxing' 때문에 뭘 써도 상관은 없다고 한다. Integer 로 리턴을 받으면 int 변수에 할당하고 자동으로 형변환이 일어나기 때문!

하지만 내부적으로 객체 생성 오버헤드가 발생 할 수 있다고한다.

728x90

'JAVA' 카테고리의 다른 글

[Java]람다와 비슷한 식  (0) 2022.07.30
[Java] Stream의 종류  (0) 2022.06.28
[Java]프로세스와 스레드의 차이  (0) 2022.04.12
[Java] 디스패치 서블릿 DispatcherServlet이란?  (0) 2022.04.11
[Java] 함수형 인터페이스란?  (0) 2022.04.09