- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Check whether the String contains only digit characters in Java
The following is our string.
String str = "4434";
To check whether the above string has only digit characters, try the following if condition that uses matches() method and checks for every character.
if(str.matches("[0-9]+") && str.length() > 2) { System.out.println("String contains only digits!"); }
Example
public class Demo { public static void main(String []args) { String str = "4434"; if(str.matches("[0-9]+") && str.length() > 2) { System.out.println("String contains only digits!"); } } }
Output
String contains only digits!
Let us see another example.
Example
public class Demo { public static void main(String []args) { String str = "5demo9"; System.out.println("String: "+str); if(str.matches("[0-9]+") && str.length() > 2) { System.out.println("String contains only digits!"); } else { System.out.println("String contains digits as well as other characters!"); } } }
Output
String: 5demo9 String contains digits as well as other characters!
- Related Articles
- Java Program to check if the String contains only certain characters
- How to check if a string contains only decimal characters?
- How to check if a string only contains certain characters in Python?
- Check if the String contains only unicode letters in Java
- How do we check in Python whether a string contains only numbers?
- Python Program to check if String contains only Defined Characters using Regex
- How to check if a unicode string contains only numeric characters in Python?
- 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 whether a String has only unicode digits in Java
- Check if a string contains only alphabets in Java using Regex
- Check if string contains special characters in Swift
- Check if the String contains only unicode letters, digits or space 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

Advertisements