Java Program to validate if a String contains only numbers


To validate if a String has only numbers, you can try the following codes. We have used the matches() method in Java here to check for number in a string.

Example

 Live Demo

public class Demo {
   public static void main(String []args) {
      String str = "978";
      System.out.println("Checking for string that has only numbers...");
      System.out.println("String: "+str);
      if(str.matches("[0-9]+") && str.length() > 2)
      System.out.println("String has only numbers!");
      else
      System.out.println("String consist of characters as well!");
   }
}

Output

Checking for string that has only numbers...
String: 978
String has only numbers!

Let us see another example, wherein our string has numbers as well as characters.

Example

 Live Demo

public class Demo {
   public static void main(String []args) {
      String str = "s987jyg";
      System.out.println("Checking for string that has only numbers...");
      System.out.println("String: "+str);
      if(str.matches("[0-9]+") && str.length() > 2)
      System.out.println("String has only numbers!");
      else
      System.out.println("String consist of characters as well!");
   }
}

Output

Checking for string that has only numbers...
String: s987jyg
String consist of characters as well!

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 26-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements