Home  >  Article  >  Java  >  How to check if a given character is a number or letter in Java?

How to check if a given character is a number or letter in Java?

WBOY
WBOYforward
2023-08-18 20:21:171325browse

How to check if a given character is a number or letter in Java?

The Character class is a subclass of the Object class, which wraps the value of the original type char in an object. An object of type Character contains a single field of type char. We can use isDigit() method of Character class to check if a given character in a string is a number/letter. The isDigit() method is a static method used to determine whether the specified character is a digit.

Example

public class CharacterIsNumberOrDigitTest {
   public static void main(String[] args) {
      String str = "Tutorials123";
      for(int i=0; i < str.length(); i++) {
         <strong>Boolean </strong>flag = <strong>Character.isDigit(str.charAt(i))</strong>;
         if(flag) {
            System.out.println("&#39;"+ str.charAt(i)+"&#39; is a number");
         }
         else {
            System.out.println("&#39;"+ str.charAt(i)+"&#39; is a letter");
         }
      }
   }
}

Output

&#39;T&#39; is a letter
&#39;u&#39; is a letter
&#39;t&#39; is a letter
&#39;o&#39; is a letter
&#39;r&#39; is a letter
&#39;i&#39; is a letter
&#39;a&#39; is a letter
&#39;l&#39; is a letter
&#39;s&#39; is a letter
&#39;1&#39; is a number
&#39;2&#39; is a number
&#39;3&#39; is a number

The above is the detailed content of How to check if a given character is a number or letter in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete