Stringからintへの変換
public static void main(String[] args) {
Integer i1 = Integer.valueOf("2");
int i2 = i1.intValue() * 3;
System.out.println(i2);
}
6
Integerからintはunboxingのため、intValue()は省略できる
public static void main(String[] args) {
Integer i1 = Integer.valueOf("2");
int i2 = i1 * 3;
System.out.println(i2);
}
6
IntegerのConstructorでもString→intできる
public static void main(String[] args) {
Integer i1 = new Integer("2");
int i2 = i1 * 3;
System.out.println(i2);
}
6
"a"をintに変換しようとするとExceptionが発生
public static void main(String[] args) {
Integer i1 = new Integer("a");
int i2 = i1 * 3;
System.out.println(i2);
}
Exception in thread "main" java.lang.NumberFormatException: For input string: "a"
なお、valueOfに似たものでparseIntがある。return typeがint。
public static void main(String[] args) {
int i1 = Integer.parseInt("2");
int i2 = i1 * 3;
System.out.println(i2);
}
6