- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
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!
- Related Articles
- Java Program to check if the String contains only certain characters
- How to find If a given String contains only letters in Java?
- Java Program to Check if a string contains a substring
- Check if a string contains only alphabets in Java using Regex
- Is it possible to check if a String only contains ASCII in java?
- Check if the String contains only unicode letters in Java
- Check if a string contains only alphabets in Java using Lambda expression
- Check if a string contains only alphabets in Java using ASCII values
- Python Program to check if String contains only Defined Characters using Regex
- Java program to check if a string contains any special character
- How to check if a string contains only decimal characters?
- How to check if a Python string contains only digits?
- Check if the String contains only unicode letters and space in Java
- Check if the String contains only unicode letters or digits in Java
- Check if a string contains numbers in MySQL?

Advertisements