본문 바로가기
언어/Java

Integer.valueOf() vs Integer.parseInt()

by 넬준 2022. 2. 21.

 

int num1 = Integer.parseInt("111");
int num2 = Integer.valueOf("111");
System.out.println(num1);  //111
System.out.println(num1);  //111

위 두 결과가 같게 나온다.

여기서 parseInt()와 valueOf()의 차이점은 무엇일까?

parseInt()

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.

 

리턴값이 int 기본자료형이다.

 

valueOf()

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.

 

리턴값이 해당 값을 가진 new Integer object이다.

즉, int num2 = Integer.valueOf("111"); 여기선 111값을 가진 새로운 Integer형 객체가 리턴되고 int형으로 auto-unboxing된 것이다.

 

 

 

'언어 > Java' 카테고리의 다른 글

String Constant Pool  (0) 2022.03.25
Overriding 오버라이딩  (0) 2022.03.14
자바 기본 - 다형성  (0) 2021.11.29
자바 기본 - 인터페이스  (0) 2021.11.29
자바 Queue에서 비슷한 메서드  (0) 2021.11.25

댓글