

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
To check if String contains only digits in Java, call matches() method on the string object and pass the regular expression "[0-9]+" that matches only if ...
Typology: Lecture notes
1 / 3
This page cannot be seen from the preview
Don't miss anything!
To check if String contains only digits in Java, call matches() method on the string object and pass the regular
digits, else it returns false. The syntax to use a String.matches() to check if String contains only digits is Example – Positive Scenario In the following program, we will take a string and check if it contains only digits using String.matches() method. Java Program Output Example – Negative Scenario In the following program, we will take a string containing some alphabets and whitespace characters. When we
String.matches("[0-9]+") public class Example { public static void main(String[] args){ String str = "5236841234"; boolean result = str.matches("[0-9]+"); System.out.println("Original String : " + str); System.out.println("Does string contain only Digits? : " + result); } } Original String : 5236841234 Does string contain only Digits? : true
In the following program, we will take a string containing some alphabets and whitespace characters. When we check if this String contains only digits using String.matches() method, we should get false as return value. Java Program Output Conclusion In this Java Tutorial, we learned how to check if given String contains only digits, using String.matches() method. ✦ Java Tutorial Java String Operations ✦ Java String ✦ Java String Operations ✦ Java - Print String to Console ✦ Java - Read String from Console ✦ Java - Concatente two Strings ✦ Java - Check if Strings are Equal ✦ Java - Find Index of First Occurrence of Substring ✦ Java - Find Index of Nth Occurrence of Substring ✦ Java - Replace First Occurrence of Substring ✦ Java - Replace All Occurrences of Substring ✦ Java - Reverse a String ✦ Java - Split String ✦ Java - Trim String public class Example { public static void main(String[] args){ String str = "ABCD 1234"; boolean result = str.matches("[0-9]+"); System.out.println("Original String : " + str); System.out.println("Does string contain only Digits? : " + result); } } Original String : ABCD 1234 Does string contain only Digits? : false