Java Program to Check if a String is Valid Number

In this java program, we will learn about how to check if a string is a valid number or not. Here we will first detect if the given String is numeric or not using parse methods and then regular expressions.

To understand this java program, you should have understanding of the following Java programming concepts:


Java Program to Check If String is Numeric using Parse Method

The simplest and most reliable approach to determine if a String is numeric or not is to parse it using Java's built-in parse methods.

  • Integer.parseInt(String)
  • Long.parseLong(String)
  • Float.parseFloat(String)
  • Double.parseDouble(String)
Above mentioned parse methods will throw NumberFormatException if the String is not a valid numeric format. If these methods don't throw any NumberFormatException, then it given string was numeric. Here is a java program to parse a floating point number.

 public class ParseFloat {
  public static void checkFloat(String str) {
    try {
      Float aFloat = Float.parseFloat(str);
      System.out.println(str + " is a valid Float");
    } catch (NumberFormatException e) {
      System.out.println(str + " is not a valid Float");
    }
  }

  public static void main(String[] args) {
    checkFloat("245.73");
    checkFloat("245.73%");
  }
}
Output
245.73 is a valid Float
245.73% is not a valid Float

Java Program to Check If String is Numeric using Regular Expressions

In this java program, we will use a regular expression to check whether a given string is a positive or negative integer or floating point number. We will use "-?\d+(\.\d+)?" regular expression to match numeric strings. Here is the breakup of this regular expression string:

  • -? : Checks for zero or more '-'(dash) characters in the string. It checks for negatove numbers. The “–” searches for dash character and the “?” marks its presence as an optional.
  • \\d+ : It searches for one or more digits in the string.
  • (\\.\\d+)? : This part of regex is searching float point numbers. It searches for one or more digits followed by a period(".") character. The question mark, in the end makes complete group is optional.

public class NumericCheckRegEx {
  public static void checkNumeric(String str) {
    boolean isNumeric = str.matches("-?\\d+(\\.\\d+)?");

    if(isNumeric) {
      System.out.println(str + " is a valid Numeric");
    } else {
      System.out.println(str + " is not a valid Numeric");
    }
  }

  public static void main(String[] args) {
    // Valid Numeric String
    checkNumeric("245");
    checkNumeric("-245");
    checkNumeric("-245.45");

    // Invalid Numeric String
    checkNumeric("tcc");
    checkNumeric("@.5");
    checkNumeric("6.");
  }
}
Output
245 is a valid Numeric
-245 is a valid Numeric
-245.45 is a valid Numeric
tcc is not a valid Numeric
@.5 is not a valid Numeric
6. is not a valid Numeric