Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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!
Advertisements