How to Check If the String Contains Only Letters or Digits

In this post, we will write a Java program to check if the String contains only Unicode letters or digits.
Program explanation:
  • This program uses Character.isLetterOrDigit(cs.charAt(i) method to check if the character is letter or digit.
  • testIsAlphanumeric() - JUnit test case for testing this program.

Java program to checks If the String Contains Only Letters or Digits

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Test;


/**
 * Program to Checks if the CharSequence contains only Unicode letters or digits
 * @author javaguides.net
 *
 */
public class IsAlphanumericExample {

 public static boolean isEmpty(final CharSequence cs) {
  return cs == null || cs.length() == 0;
 }
 
 public static boolean isAlphanumeric(final CharSequence cs) {
  if (isEmpty(cs)) {
   return false;
  }
  final int sz = cs.length();
  for (int i = 0; i < sz; i++) {
   if (!Character.isLetterOrDigit(cs.charAt(i))) {
    return false;
   }
  }
  return true;
 }
 
 @Test
 public void testIsAlphanumeric() {
  assertFalse(isAlphanumeric(null));
  assertFalse(isAlphanumeric(""));
  assertFalse(isAlphanumeric(" "));
  assertTrue(isAlphanumeric("a"));
  assertTrue(isAlphanumeric("A"));
  assertTrue(isAlphanumeric("kgKgKgKgkgkGkjkjlJlOKLgHdGdHgl"));
  assertFalse(isAlphanumeric("ham kso"));
  assertTrue(isAlphanumeric("1"));
  assertTrue(isAlphanumeric("hkHKHik6iUGHKJgU7tUJgKJGI87GIkug"));
  assertFalse(isAlphanumeric("_"));
  assertFalse(isAlphanumeric("hkHKHik*khbkuh"));
 }
}
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Related String Programs

Note that these programs are asked in interviews.
If you like my articles/guides then connect with me directly on Google Plus, Facebook, LinkedIn, GitHub, and StackOverflow.
Please comment if you have any suggestions or feedback about my articles would be appreciated.
Happy learning and keep coding !!!.

Comments