Java
Java - String을 int로 변환하기
codeManager
2022. 7. 15. 20:41
반응형
String 문자열을 int(Integer)로 바꾸는 방법입니다.
1. Integer.parseInt()
class StringToInt {
public static void main(String[] args) {
String str = "123";
int num = Integer.parseInt(str);
System.out.println(num);
}
}
결과
123
2. Integer.valueOf()
class StringToInt {
public static void main(String[] args) {
String str = "123";
int num = Integer.valueOf(str);
System.out.println(num);
}
}
결과
123
3. Exception 처리
class StringToInt {
public static void main(String[] args) {
String str = "123a";
int num = Integer.valueOf(str);
System.out.println(num);
}
}
String이 숫자가 아닌 경우에는 NumberFormatException이 발생하므로 예외처리가 필요합니다.
결과
Exception in thread "main" java.lang.NumberFormatException: For input string: "123a"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.valueOf(Integer.java:983)
at StringToInt.main(StringToInt.java:7)
관련글
Java - byte[]를 String으로 변환
자바에서 String을 byte[] 로 변환하여 파일에 저장하거나, 데이터로부터 byte[]를 읽어와서 String으로 변환할 수 있습니다. 1. String to byte[], byte[] to String class BytesToString { public static void m..
codemanager.tistory.com
반응형