Saturday, September 5, 2009

Java - convert String to int, double, long, float

We can convert a String to int by two ways



Way one

String str="20";
int val = Integer.parseInt(str);

and the other way is

String str="20";
int val = Integer.valueOf(str).intValue();

For converting a String to double



String str="20";
double val = Double.valueOf(str).doubleValue();

For converting a String to long



we convert like this

String str="20";
long val = Long.valueOf(str).longValue();

there is also another way

String str="20";
long l = Long.parseLong(str);

Likewise converting a String to float is



String str="20";
float val = Float.valueOf(str).floatValue();