Question

How do I convert from a string into a number?

Answer

The first thing you have to be sure of is that your string actually contains a number! If not, then you'll generate a NumberFormatException. We can use the Integer class for converting from a string into an integer (or if we're dealing with decimal numbers, we can use the Double class).

The follow example shows how to convert from a string to an integer.

String numberOne = "123";
String numberTwo = "456";

// Convert numberOne and numberTwo to an int with Integer class
Integer myint1 = Integer.valueOf(numberOne);
Integer myint2 = Integer.valueOf(numberTwo);
// Add two numbers together
int number = myint1.intValue() + myint2.intValue();

You'll notice that when we need to use numbers as a data type (int), we need to convert from an Integer to an int. Confused? An Integer acts as a wrapper for our int data type (making conversion from String to number easy). When we want to use the data type, we call the intValue() method, which returns an int.


Back