When creating a program we will use a lot of string to represent our data. The data might not just information about our customer name, email or address, but will also contains numeric data represented as string. So how do we know if this string contains a valid number?
Java provides some wrappers to the primitive data types that can be used to do the checking. These wrappers come with the parseXXX()
method such as Integer.parseInt()
, Float.parseFloat()
and Double.parseDouble()
methods.
package org.kodejava.example.lang;
public class NumericParsingExample {
public static void main(String[] args) {
String age = "15";
String height = "160.5";
String weight = "55.9";
try {
int theAge = Integer.parseInt(age);
float theHeight = Float.parseFloat(height);
double theWeight = Double.parseDouble(weight);
System.out.println("Age = " + theAge);
System.out.println("Height = " + theHeight);
System.out.println("Weight = " + theWeight);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
}
In the example code we use Integer.parseInt()
, Float.parseFloat()
, Double.parseDouble()
methods to check the validity of our numeric data. If the string is not a valid number java.lang.NumberFormatException
will be thrown.
The result of our example:
Age = 15
Height = 160.5
Weight = 55.9
- How do I create a generic class in Java? - January 1, 2021
- How do I convert java.util.TimeZone to java.time.ZoneId? - April 25, 2020
- How do I get a list of all TimeZones Ids using Java 8? - April 25, 2020