Javaの変換メソッド
Javaには文字列を数値型に変換する、数値型を文字列に変換する様々なメソッドがあります。
文字列を変換するvalueOf、Parseメソッド
valueOfメソッドで文字列(String型)を数値(Byte、Short、Integer、Long型など)に変換します。Parseメソッドで文字列(String型)を数値(byte、short、int、long型など)に変換します。
//文字列をByte型に変換 Byte b1 = Byte.valueOf("1"); //文字列をbyte型に変換 byte b2 = Byte.valueOf("1").byteValue(); //文字列をShort型に変換 Short s1 = Short.valueOf("1"); //文字列をshort型に変換 short s2 = Short.valueOf("1").shortValue(); //文字列をInteger型に変換 Integer i1 = Integer.valueOf("1"); //文字列をint型に変換 int i2 = Integer.valueOf("1").intValue(); //文字列をLong型に変換 Long l1 = Long.valueOf("1"); //文字列をlong型に変換 long l2 = Long.valueOf("1").longValue(); //文字列をFloat型に変換 Float f1 = Float.valueOf("1"); //文字列をfloat型に変換 float f2= Float.valueOf("1").floatValue(); //文字列をDouble型に変換 Double d1 = Double.valueOf("1"); //文字列をdouble型に変換 double d2 = Double.valueOf("1").doubleValue(); //文字列をbyte型に変換 byte b3 = Byte.parseByte("1"); //文字列をshort型に変換 short s3 = Short.parseShort("1"); //文字列をint型に変換 int i3 = Integer.parseInt("1"); //文字列をlong型に変換 long l3 = Long.parseLong("1"); //文字列をfloat型に変換 float f3 = Float.parseFloat("1"); //文字列をdouble型に変換 double d3 = Double.parseDouble("1");
数値を文字列に変換するtoStringメソッド
toStringメソッドで数値(byte、short、int、long型など)を文字列(String型)に変換します。toStringメソッドは、引数に指定された変数型を文字列に変換することが出来ます。String str; //byte型を文字列に変換 str = Byte.toString(b2); //short型を文字列に変換 str = Short.toString(s2); //int型を文字列に変換 str = Integer.toString(i2); //long型を文字列に変換 str = Long.toString(l2); //float型を文字列に変換 str = Float.toString(f2); //double型を文字列に変換 str = Double.toString(d2);