DEV Community

Cover image for How to check if a character is a number in java?
bingchandler671
bingchandler671

Posted on

How to check if a character is a number in java?

Hi, I am new to this world of programming in java language. You might feel to check if a character is a number in java? I mean what is the best way to do it?

Solution:

I'm not sure if this is the best option or not, But this seems pretty simple to me. We can check whether the given character is a number or not by using the isDigit() method of Character class. This method returns true if the passed character is really a digit.

Please check out the example below:

public class CharacterCheck {
   public static void main(String[] args) {
      String s = "ABC123";
      for(int Count=0; Count < s.length(); Count++) {
         Boolean ReturnValue = Character.isDigit(s.charAt(Count));
         if(ReturnValue) {
            System.out.println("'"+ s.charAt(Count)+"' = Num");
         }
         else {
            System.out.println("'"+ s.charAt(Count)+"' = NAN");
         }
      }
   }
}

Enter fullscreen mode Exit fullscreen mode

Output

'A' = NAN
'B' = NAN
'C' = NAN
'1' = Num
'2' = Num
'3' = Num
Enter fullscreen mode Exit fullscreen mode

Also there is alternatine method, read alternative

Top comments (1)

Collapse
 
dhyces profile image
dhyces

Arrays.stream(s.charArray()).forEach(c -> System.out.println(c + " " + Character.isDigit(c)));
This is just to do exactly what you did in your example. Depending on what you're doing with the result, you might want to use a different method.