• Courses
  • Tutorials
  • Jobs
  • Practice
  • Contests
September 02, 2022 |680 Views
Java program to Check whether the String contains only digits
  Share   Like
Description
Discussion

In this video, we will check whether the string contains only digits in Java.

Example:

1. Input: string = “7895668”
    Output: True
    Explanation: The given string contains only digits so the output is true.

2. Input: string = “GeeksforGeeks2022”
    Output: false
   Explanation: The given string contains alphabet characters and digits so the output is false.

Here we see three different types of methods for checking strings containing only digits in Java:

  1. Using traversal: Here we traverse each character of the input string. Then we check if the character of the string contains only digits from 0 to 9. If this condition is true then print “True” otherwise print “False”.
  2. Using character.isDigit(Char Ch): This is an in-built function of Java. It simply checks whether each character of the string is a digit or not.
  3. Using Regular Expression: In this method, we create a Regular Expression to check string contains only digits as mentioned below: regex = "[0-9]+"; Here we match the given string with a Regular Expression. In Java, this can be done by using Pattern. matcher(). It prints true if the string matches with the given regular expression, otherwise return false.

How to check if string contains only digits in Java: https://www.geeksforgeeks.org/how-to-check-if-string-contains-only-digits-in-java/