Check whether a String has only unicode digits in Java


In order to check if a String has only unicode digits in Java, we use the isDigit() method and 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)

where the parameter codePoint represents the character to be checked.

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 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
         if ((Character.isDigit(s.charAt(i)) == false) ) {
            return false; // if it is not a digit then it will return false
         }
      }
      return true;
   }
   public static void main(String [] args) {
      Example e = new Example();
      String s = "1024"; // has only unicode digits so it will return true
      String s1 = "13f4"; // has digits as well as so it will return false
      System.out.println("String "+s+" has only unicode digits : "+e.check(s));
      System.out.println("String "+s1+" has only unicode digits : "+e.check(s1));
   }
}

Output

String 1024 has only unicode digits : true
String 13f4 has only unicode digits : false

Updated on: 26-Jun-2020

320 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements