7. Converting a string into an int, long, float, or double

Let's consider the following strings (negatives can be used as well):

private static final String TO_INT = "453"; 
private static final String TO_LONG = "45234223233";
private static final String TO_FLOAT = "45.823F";
private static final String TO_DOUBLE = "13.83423D";

A proper solution for converting String into int, long, float, or double consists of using the following Java methods of the Integer, Long, Float, and Double classes—parseInt(), parseLong(), parseFloat(), and parseDouble():

int toInt = Integer.parseInt(TO_INT);
long toLong = Long.parseLong(TO_LONG);
float toFloat = Float.parseFloat(TO_FLOAT);
double toDouble = Double.parseDouble(TO_DOUBLE);

Converting String into an Integer, Long, Float, or Double object can be accomplished via the following Java methods—Integer.valueOf(), Long.valueOf(), Float.valueOf(), and Double.valueOf():

Integer toInt = Integer.valueOf(TO_INT);
Long toLong = Long.valueOf(TO_LONG);
Float toFloat = Float.valueOf(TO_FLOAT);
Double toDouble = Double.valueOf(TO_DOUBLE);

When a String cannot be converted successfully, Java throws a NumberFormatException exception. The following code speaks for itself:

private static final String WRONG_NUMBER = "452w";

try {
Integer toIntWrong1 = Integer.valueOf(WRONG_NUMBER);
} catch (NumberFormatException e) {
System.err.println(e);
// handle exception
}

try {
int toIntWrong2 = Integer.parseInt(WRONG_NUMBER);
} catch (NumberFormatException e) {
System.err.println(e);
// handle exception
}
For third-party library support, please consider Apache Commons BeanUtils: IntegerConverter, LongConverter, FloatConverter, and DoubleConverter.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.136.226