Learn Java by Example: Java Program to Check if a String is Numeric

Java Program to Check if a String is Numeric

In this program, you’ll learn different techniques to check if a string is numeric or not in Java.

 


Example 1: Check if a string is numeric


public class Numeric{

    public static void main(String[] args){

        String string = "12345.15";
        boolean numeric = true;

        try {
            Double num = Double.parseDouble(string);
        } catch (NumberFormatException e) {
            numeric = false;
        }

        if(numeric)
            System.out.println(string + " is a number");
        else
            System.out.println(string + " is not a number");
    }
}

Output

12345.15 is a number

In the above program, we have a String named string that contains the string to be checked. We also have a boolean value numeric which stores if the final result is numeric or not.

To check if the string contains numbers only, in the try block, we use Double‘s parseDouble() method to convert the string to a Double.

If it throws an error (i.e. NumberFormatException error), it means the string isn’t a number and numeric is set to false. Else, it’s a number.

However, if you want to check if for a number of strings, you would need to change it to a function. And, the logic is based on throwing exceptions, this can be pretty expensive.

Instead, we can use the power of regular expressions to check if the string is numeric or not as shown below.


Example 2: Check if a string is numeric or not using regular expressions (regex)


public class Numeric{

    public static void main(String[] args){

        String string = "-1234.15";
        boolean numeric = true;

        numeric = string.matches("-?\d+(\.\d+)?");

        if(numeric)
            System.out.println(string + " is a number");
        else
            System.out.println(string + " is not a number");
    }
}

Output

-1234.15 is a number

In the above program, instead of using a try-catch block, we use regex to check if string is numeric or not. This is done using String’s matches() method.

In the matches() method,

  • -? allows zero or more - for negative numbers in the string.
  • \d+ checks the string must have at least 1 or more numbers (\d).
  • (\.\d+)? allows zero or more of the given pattern (\.\d+) in which
    • \. checks if the string contains . (decimal points) or not
    • If yes, it should be followed by at least one or more number \d+.

 

Python Example for Beginners

Two Machine Learning Fields

There are two sides to machine learning:

  • Practical Machine Learning:This is about querying databases, cleaning data, writing scripts to transform data and gluing algorithm and libraries together and writing custom code to squeeze reliable answers from data to satisfy difficult and ill defined questions. It’s the mess of reality.
  • Theoretical Machine Learning: This is about math and abstraction and idealized scenarios and limits and beauty and informing what is possible. It is a whole lot neater and cleaner and removed from the mess of reality.

Data Science Resources: Data Science Recipes and Applied Machine Learning Recipes

Introduction to Applied Machine Learning & Data Science for Beginners, Business Analysts, Students, Researchers and Freelancers with Python & R Codes @ Western Australian Center for Applied Machine Learning & Data Science (WACAMLDS) !!!

Latest end-to-end Learn by Coding Recipes in Project-Based Learning:

Applied Statistics with R for Beginners and Business Professionals

Data Science and Machine Learning Projects in Python: Tabular Data Analytics

Data Science and Machine Learning Projects in R: Tabular Data Analytics

Python Machine Learning & Data Science Recipes: Learn by Coding

R Machine Learning & Data Science Recipes: Learn by Coding

Comparing Different Machine Learning Algorithms in Python for Classification (FREE)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.