Java Program to Check if a String is a Pangram

In this tutorial, I will be sharing what is Pangram in java, examples of Pangram, algorithm, and java program to check if a given String is a Pangram or not.

Read Also:  How to Check String contains Special Characters in Java 

What is Pangram String in Java

According to Wikipedia,

A String is called Pangram if it is using every letter of a given alphabet at least once. In simple words, if a String contains all the 26 letters of English alphabet at least once.
Examples of Pangram:

Given String: "The quick brown fox jumps over the lazy dog"  
Is Given String Pangram : Yes 
 
Given String: "The five boxing wizards jump quickly"  
Is Given String Pangram : Yes  

Below are examples of String which are NOT Pangram:

Given String: "Father of Java programming language is James Gosling"  
Is Given String Pangram : No 
List of Missing letters : 'b','c','d','k','q','w','x','y','z' 
 
Given String: "Do you know how many total keywords present in Java"  
Is Given String Pangram : No 
List of Missing letters : 'b','c','f','g','q','x','z' 

Java Program for Pangram String

Below is the simple java program for Pangram String.

import java.util.HashSet;
public class JavaHungry {
    public static void main(String args[]) {
      // Given String    
      String inputString = "Do you know how many total keywords present in Java";
      
      /* Convert inputString to lowercase and remove all
      whitespaces by using replaceAll() method */
      inputString = inputString.toLowerCase().replaceAll(" ","");
      
      // Convert inputString to char array 
      char[] arr = inputString.toCharArray();
      
      // Initialize HashSet
      HashSet<Character> set = new HashSet<>();
      
      // Iterating char array 
      for(char ch : arr)
      {
          set.add(ch);
      }
      
      // If set size is 26 then inputString is Pangram otherwise not
      if(set.size() == 26)
        System.out.println("Input String is Pangram");
      else
        System.out.println("Input String is NOT Pangram");
    }
}

Output:
Input String is NOT Pangram

Algorithm for Pangram String

1. Convert all the characters of inputString to lowercase using the toLowerCase() method and replace all the whitespace characters using the replaceAll(String, String) method.

2. Convert inputString to Character array using toCharArray() method. Iterate through the Character array and add each character to the HashSet object.

3. Since Pangram contains all the 26 letters of the English alphabet, so if the size of the HashSet is also 26 then the inputString is Pangram otherwise not.

That's all for today, please mention in comments in case you have any questions related to Java program to check if a String is a Pangram or not.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry