Java program to check if a string contains only alphabets using Lambda expression

With strings, the task is to check if the string contains only letters or not.

Examples:

Input : GeeksforGeeks
Output : True

Input : Geeks4Geeks
Output : False

Input : null
Output : False

The idea is to use isLetter() method of Character class.

Algorithm:

  1. Take the rope
  2. string match:
    i. Check if string is empty or not. If empty, return false
    ii. Check if the string is null or not. If it's null, return false.
    iii. If the string is not empty or null,
    Then check with Lambda Expression Character::isLetter().
  3. Return true if match

Pseudocode:

public static boolean isStringOnlyAlphabet(String str)
{
	return ((!str.equals(""))
			&& (str != null)
			&& (str.chars().allMatch(Character::isLetter)));
}

Program: Checking if String contains only Alphabets.

// Java program to check if String contains only Alphabets
// using Lambda Expression

class GFG {

	// Function to check String for only Alphabets
	public static boolean isStringOnlyAlphabet(String str)
	{
		return ((str != null)
				&& (!str.equals(""))
				&& (str.chars().allMatch(Character::isLetter)));
	}

	// Main method
	public static void main(String[] args)
	{

		// Checking for True case
		System.out.println("Test Case 1:");

		String str1 = "GeeksforGeeks";
		System.out.println("Input: " + str1);
		System.out.println("Output: " + isStringOnlyAlphabet(str1));

		// Checking for String with numeric characters
		System.out.println("\nTest Case 2:");

		String str2 = "Geeks4Geeks";
		System.out.println("Input: " + str2);
		System.out.println("Output: " + isStringOnlyAlphabet(str2));

		// Checking for null String
		System.out.println("\nTest Case 3:");

		String str3 = null;
		System.out.println("Input: " + str3);
		System.out.println("Output: " + isStringOnlyAlphabet(str3));

		// Checking for empty String
		System.out.println("\nTest Case 4:");

		String str4 = "";
		System.out.println("Input: " + str4);
		System.out.println("Output: " + isStringOnlyAlphabet(str4));
	}
}

Output:

Test Case 1:
Input: GeeksforGeeks
Output: true

Test Case 2:
Input: Geeks4Geeks
Output: false

Test Case 3:
Input: null
Output: false

Test Case 4:
Input: 
Output: false

 

Submit Your Programming Assignment Details