by Sai gowtham

How to check if a given string is number in Java

To check whether a given string is number or not, we can use the string.chars().allMatch() method where it returns true if a string is number else it returns false.

Here is an example:

public class Main
{
    public static void main(String[] args) {

            String myString = "9291";
            boolean isNumeric = myString.chars().allMatch( Character::isDigit );
            if(isNumeric)
            System.out.println(myString + " is a number");
          else
            System.out.println(myString + " is not a number");
    }
}

Output:

9291 is a number

False case

public class Main
{
    public static void main(String[] args) {

            String myString = "hello fashion";
            boolean isNumeric = myString.chars().allMatch( Character::isDigit );
            if(isNumeric)
            System.out.println(myString + " is a number");
          else
            System.out.println(myString + " is not a number");
    }
}

Output:

hello fashion is not a number

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course