Home > Java > javaTutorial > body text

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

WBOY
Release: 2023-08-18 20:21:17
forward
1311 people have browsed it

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");
         }
      }
   }
}
Copy after login

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
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!