English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java program to check if a string contains only numbers

To verify if a string only contains numbers, you can try the following code. Wematches()Here we use the method in Java to check for numbers in a string.

Example

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

Output Result

Checking for a string that only contains numbers...
String: 978
Strings only contain numbers!

Let's look at another example where our string contains both numbers and characters.

Example

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

Output Result

Checking for a string that only contains numbers...
String: s987jyg
Strings also contain characters!