The java Character class isdigit() method returns true if the argument is a digit. It is a static method, and its declaration is as follows:
public static boolean isDigit(char ch)
The method accepts a character as an argument and returns a boolean value indicating whether the passed character is a digit or not. If the passed character is between '0' and '9', it returns true. Otherwise, it returns false.
Example 1 - Check if a character is a digit:
char ch = '7'; if (Character.isDigit(ch)) { System.out.println("The character is a digit."); } else { System.out.println("The character is not a digit."); }
Output: The character is a digit.
Example 2 - Check if a string contains only digits:
String str = "12345"; boolean onlyDigits = true; for (int i = 0; i < str.length(); i++) { if (!Character.isDigit(str.charAt(i))) { // the character is not a digit onlyDigits = false; break; } } if (onlyDigits) { System.out.println("The string contains only digits."); } else { System.out.println("The string does not contain only digits."); }
Output: The string contains only digits.
The Character class belongs to the java.lang package, so you do not need to import any additional library to use its methods.
Java Character.isDigit - 30 examples found. These are the top rated real world Java examples of Character.isDigit extracted from open source projects. You can rate examples to help us improve the quality of examples.