Wednesday, April 11, 2007

Converting between Primitive Types and String

Converting between Primitive Types and String
From To Example
byte String byte b = -127; String s = Byte.toString(b);
int String int i = 1450; String s = Integer.toString(i);
String int String s = "1335"; int i = Integer.parseInt(s);

The Integer.toString() method is typically used to convert an integer to a String. Also, Integer.toString() is preferred to String.valueOf(), because String.valueOf() ends up calling Integer.toString() anyway.

Do not write int i = 8100; String s = String.valueOf(i);, because it is inefficient to use public static String valueOf(int i) { from class String. Use public static String toString(int i) { from class Integer instead. public static String valueOf(int i) { from class String simply calls public static String toString(int i, int radix) { from class Integer which in turn calls public static String toString(int i) { from class Integer.

Similarly, use code like byte b = Byte.parseByte("35"); for converting bytes.