본문 바로가기

Programming/JAVA

java : 문자열을 int형으로 형변환할때 주의점(parseInt, valueOf)

대부분 학교에서나 어디에서나 parseInt를 주로 사용하고 배우기때문에 큰 의미가 없겠으나.............

parseInt는 문자열로 된 정수의 표현이 음수까지 인식하고 리턴한다.
하지만 valueOf는 음수를 인식하지 못하고 온전히 양수로만 parsing하여 리턴.

또한 valueOf는 내부적으로 parseInt를 사용하고 있기때문에 성능면에서도 parseInt보다 효율적이지 못하다.

물론 둘의 성향은 다르지만 ;; (parseInt(String s) : int    /     valueOf(String s) : Integer

parseInt
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. 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.
___________________________________________________________________________
valueOf
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.