본문 바로가기

old/Programming

[java]String to int, int to String 형변환 casting variables

반응형






String -> int

Integer.parseInt()

 

      int Num = Integer.parseInt(Str);



int -> String 

String.valueOf()


     String Str = String.valueOf(Num);




과정



사실 형변환에는 위의 방법 말고도 여러가지 방법이 있습니다.

하지만, 여러가지 찾아본 결과 위의 방법이 가장 알맞다고 생각합니다.



String -> int


1. Integer.parseInt(string);

2. Integer.valueOf(string);


int -> String 


3. String.valueOf(number) and Integer.toString(number)

4. number + ""




1. [String -> int] Integer.parseInt(string);


자바 api에서 위 메서드를 찾아보면


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.


String을 Int형으로 바꿔주고 int형으로 값을 리턴한다는 것을 알수 있습니다.

int형으로 값을 리턴한다는것이 중요합니다.


2. [String -> int]] Integer.valueOf(string);


마찬가지로 자바 api에서 위 메서드를 찾아보면


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:


쉽게 말해서 value안에서 parseInt메서드를 사용하여 변환하는 것입니다. 단, 위의 parseInt메서드와 다른점은 integer object형으로 리턴한다는 것 입니다. 자바에서 integer과 int는 서로 다른 데이터 타입인데, integer은 참조형(Reference type)이고, int는 기본형(Primitive type)입니다.


위를 정확하게 이해하기 위해서는 몇가지 개념을 이해할 필요가 있습니다.


기본형 데이터 타입 (Primitive data type)

-boolean, char, byte, short, int, long, float, double, 이 8가지 데이터 타입을 말합니다

-null값이 할당될수 없습니다.

참조형 데이터 타입 (Reference data type)

-위의 8가지를 제외한 나머지 데이터 타입을 말합니다.

-유식하게 표현해서, 객체의 주소를 저장한다고 합니다.



오토박싱 (autoboxing)과 언박싱 (Unboxing)이란?



그러므로, String 에서 int로 형변환시, 위 두가지 방법을 고려하여 버그나지 않도록 코딩하는게 중요합니다.



3. [int -> String] String.valueOf(number) and Integer.toString(number)


자바 api를 에서 String.valueOf를 찾아보면...


Returns the string representation of the int argument.

The representation is exactly the one returned by the Integer.toString method of one argument.


아예 Integer.toString랑 똑같다고 명시되어 있습니다.

굳이 고민할 필요 없이 내키는데로 사용하면 됩니다.



4. [int -> String] number + ""


솔직히, 이 방법은 도대체 어디서 나온건지 도무지 알수가 없었습니다.

API를 마구 뒤져도 안나오고 Stackoverflow와 구글에 아무리 검색을 해도 정확한 연원을 찾을수가 없더군요.


아마 옛날에 개발하다 넣어진 잔재라고 생각합니다.


stackoverflow에서 확인한바에 따르면, 다른 두가지 방법에 비하여 두배는 느리다는 것 입니다.





반응형