String 문자열을 int로 변환하기 위해서는
java.lang.Integer 클래스의 parseInt()와 valueOf() 메소드를 사용할 수 있습니다.
Integer.parseInt()
static int parseInt(String s)
java.lang.Integer 클래스의 static 메소드인 parseInt() 메소드는
파라미터로 숫자로 변환할 문자열을 입력받고,
입력받은 문자열을 integer로 변환한 int 값을 리턴합니다.
public class StringToInt {
public static void main(String[] args) {
String str1 = "123";
String str2 = "-123";
int intValue1 = Integer.parseInt(str1);
int intValue2 = Integer.parseInt(str2);
System.out.println(intValue1); // 123
System.out.println(intValue2); // -123
}
}
/* 결과
123
-123
*/
Integer.valueOf()
static int valueOf(String s)
parseInt() 메소드와 마찬가지로
valueOf() 메소드는 java.lang.Integer 클래스의 static 메소드이고,
파라미터로 숫자로 변환할 문자열을 입력받습니다.
parseInt() 와 가장 큰 차이점은,
valueOf() 메소드는 문자열을 변환하여 Integer Object를 리턴한다는 것입니다.
parseInt() 메소드는 primitive type인 int를 리턴합니다.
(parseInt()와 valueOf()는 이 외에도 입력받는 파라미터의 타입 등의 차이점이 더 있습니다.)
public class StringToInt {
public static void main(String[] args) {
String str1 = "123";
String str2 = "-123";
int intValue1 = Integer.valueOf(str1).intValue();
int intValue2 = Integer.valueOf(str2).intValue();
System.out.println(intValue1); // 123
System.out.println(intValue2); // -123
}
}
/* 결과
123
-123
*/