Check if the String contains only unicode letters or digits in Java


To check whether a String contains only unicode letters or digits in Java, we use the isLetterOrDigit() method and charAt() method with decision-making statements.

The isLetterOrDigit(char ch) method determines whether the specific character (Unicode ch) is either a letter or a digit. It returns a boolean value, either true or false.

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

public static boolean isLetter(char ch)

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 in Java to check whether a String contains only Unicode letters or digits.

Example

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 neither a letter nor a digit
         // if it is neither a letter nor a digit then it will return false
         if ((Character.isLetterOrDigit(s.charAt(i)) == false)) {
            return false;
         }
      }
      return true;
   }
   public static void main(String [] args) {
      Example e = new Example();
      String s = "10@4"; // returns false due to special character presence
      String s1 = "13y4"; // returns true
      String s2 = "1000"; // returns true
      String s3= "abcd"; // returns true
      System.out.println("String "+s+" has only unicode letters or digits : "+e.check(s));
      System.out.println("String "+s1+" has only unicode letters or digits : "+e.check(s1));
      System.out.println("String "+s2+" has only unicode letters or digits : "+e.check(s2));
      System.out.println("String "+s3+" has only unicode letters or digits : "+e.check(s3));
   }
}

Output

String 10@4 has only unicode letters or digits : false
String 13y4 has only unicode letters or digits : true
String 1000 has only unicode letters or digits : true
String abcd has only unicode letters or digits : true

Updated on: 26-Jun-2020

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements