There are many ways to check if String is numeric in Java. Here, we will explore the following:
- By parsing it using the built-in methods from Wrapper classes
- Using the isCreatable() method from the NumberUtils class
- Using the isNumeric() method from the StringUtils class
Using the built-in methods from Wrapper classes
We have the following methods that we can use to check if String is numeric in Java:
- Integer.parseInt(String)
- Float.parseFloat(String)
- Double.parseDouble(String)
- Long.parseLong(String)
If we don’t get the NumberFormatException while executing them, then it means that the parsing was successful, and the provided String is a number.
You can check out this tutorial Exception Handling in Java for more information on how to handle exceptions in Java.
Example
public class Test { public static void main(String[] args) { String str = "1849231"; try { Integer.parseInt(str); Float.parseFloat(str); Double.parseDouble(str); Long.parseLong(str); System.out.println("No error occurred. String is numeric!"); } catch (NumberFormatException e) { System.out.println("String is not numeric!"); } } }
public class Test { public static void main(String[] args) { String str = "1893a"; try { Integer.parseInt(str); Float.parseFloat(str); Double.parseDouble(str); Long.parseLong(str); System.out.println("No error occurred. String is numeric!"); } catch (NumberFormatException e) { System.out.println("NumberFormatException occurred. String is not numeric!"); } } }
Using the isCreatable() method from the NumberUtils class
Another good way to check if String is numeric in Java is to use the isCreatable() method from the NumberUtils class that belongs to the Apache Commons library. This method checks whether the String is a valid Java number and returns boolean, so we are not expecting any errors if the String is not numeric.
To use it, you need to add the corresponding dependency to your project.
Example
import org.apache.commons.lang3.math.NumberUtils; public class Test { public static void main(String[] args) { System.out.println(NumberUtils.isCreatable("1297438123")); System.out.println(NumberUtils.isCreatable("123ab")); } }
Using the isNumeric() method from the StringUtils class
We also have one useful method isNumeric() from the StringUtils class that belongs to the Apache Commons library. You need to add the dependency to your project to be able to use it.
Example
import org.apache.commons.lang3.StringUtils; public class Test { public static void main(String[] args) { System.out.println(StringUtils.isNumeric("1297438123")); System.out.println(StringUtils.isNumeric("123a")); } }