![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
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
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!
Advertisements