How to Check if the String Contains only Letters

In this post, we will write a Java program to check if the String contains only Unicode letters.
Program explanation:
  1. This program uses Character.isLetter(cs.charAt(i) method to check if the character is letter or not.
  2. testIsAlpha() JUnit test case for testing this program.

How to Check if the String Contains only Letters

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

import org.junit.Test;

/**
 * Checks if the CharSequence contains only Unicode letters
 * @author javaguides.net
 *
 */
public class IsAlphaExample {
 
 public static boolean isAlpha(final CharSequence cs) {
  if (isEmpty(cs)) {
   return false;
  }
  final int sz = cs.length();
  for (int i = 0; i < sz; i++) {
   if (!Character.isLetter(cs.charAt(i))) {
    return false;
   }
  }
  return true;
 }
 
 public static boolean isEmpty(final CharSequence cs) {
  return cs == null || cs.length() == 0;
 }
 
 @Test
 public void testIsAlpha() {
  assertFalse(isAlpha(null));
  assertFalse(isAlpha(""));
  assertFalse(isAlpha(" "));
  assertTrue(isAlpha("a"));
  assertTrue(isAlpha("A"));
  assertTrue(isAlpha("kgKgKgKgkgkGkjkjlJlOKLgHdGdHgl"));
  assertFalse(isAlpha("ham kso"));
  assertFalse(isAlpha("1"));
  assertFalse(isAlpha("hkHKHik6iUGHKJgU7tUJgKJGI87GIkug"));
  assertFalse(isAlpha("_"));
  assertFalse(isAlpha("hkHKHik*khbkuh"));
 }
}

Related String Programs

Note that these programs are asked in interviews.

Comments