Stringを整数に変換


下の2つのsampleは結果的に同じです。
最初のsampleは String -> Integer -> int と変換しています。
2つ目のサンプルはIntegerクラスを使って、String -> int と変換しています。


public class ConvertStoI { public static void main(String[] args){ //String Object -> Integer Object Integer integer1 = new Integer("7"); Integer integer2 = new Integer("8"); // Integer Object -> int int int1 = integer1.intValue(); int int2 = integer2.intValue(); int int3 = int1 + int2; System.out.println(int3); } } class ExamparseInt { public static void main(String[] args){ int i1 = Integer.parseInt("7"); int i2 = Integer.parseInt("8"); int i3 = i1 + i2; System.out.println(i3); }
}


実行結果
結果は1つ目のコードも2つ目のコードも15とコンソールに表示されます。

Integer class
Integerクラスは 基本型 intに対応するクラスです。
Integer にすることで intを算術演算以外に使用できます。(型変換など)
Integerは算術演算で直接使うことはできません。

Integer.parseInt() methodはIntegerクラスのstaicなメソッドですが、
他のwrapperクラスにも同じ機能の(String -> )parseXXX()メソッドがあります。
つまり、他のdouble,float,longなども同様にWRAPクラスを使って、文字型から数値に変換できます。
例えばLongクラスであれば、Long.parseLong(String s)を使って基本型のlongを入手できます。

これらはJDK1.2以降で新しく、型変換の為のメソッドとして提供されました。


intに関わる変換メソッド

int(primitive type) String.valueOf(int)
String
Integer.parseInt(String)
Integer(int) integer.intValue()
Integer integer.toString()

String
Integer.valueOf(String)