Check if the String has only unicode digits or space in Java


In order to check if a String has only unicode digits or space in Java, we use the isDigit() method and the charAt() method with decision making statements.

The isDigit(int codePoint) method determines whether the specific character (Unicode codePoint) is a digit. It returns a boolean value, either true or false.

Declaration - The java.lang.Character.isDigit() method is declared as follows −

public static boolean isDigit(int codePoint)

The charAt() method returns a character value at a given index. It belongs to the String class in Java. The index must be between 0 to length()-1.

Declaration − The java.lang.String.charAt() method is declared as follows −

public char charAt(int index)

Let us see a program to check whether a String has only unicode digits or space in Java.

Example

 Live Demo

public class Example {
   boolean check(String s) {
    if (s == null) // checks if the String is null {
      return false;
    }
      int len = s.length();
      for (int i = 0; i < len; i++) {
         // checks whether the character is not a digit and not a space
            if ((Character.isDigit(s.charAt(i)) == false) && (s.charAt(i) != ' ')) {
            return false; // if it is not any of them then it returns false
         }
      }
      return true;
   }
   public static void main(String [] args) {
      Example e = new Example();
      String s = "0090"; // has only digits so it will return true
      String s1 = "y o y"; // has spaces but also has letters so it will return false
      System.out.println("String "+s+" has only unicode digits or spaces: "+e.check(s));
      System.out.println("String "+s1+" has only unicode digits or spaces: "+e.check(s1));
   }
}

Output

String 0090 has only unicode digits or spaces: true
String y o y has only unicode digits or spaces: false

Updated on: 26-Jun-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements