Write Java program to print used different characters (letters) in a string


This Java program takes input from the user in the form of a string and then counts the total number of different characters used in that string.

Here is how the program works:

  • The user is prompted to enter a string..
  • The string is converted to uppercase, so that we only need to check for uppercase letters A to Z..
  • The program then loops through all uppercase letters A to Z and checks if each character is present in the string..
  • If a character is present in the string, it is printed on the console and a count is incremented..
  • At the end of the loop, the program displays the total number of different characters used in the string.

Source Code

import java.util.Scanner; 
public class Different_Char
{    
	public static void main(String[] args)
	{    
		String text;
		int count;
		char ch;       
		Scanner input = new Scanner(System.in);
 
		System.out.print("Enter the String : ");
		text = input.nextLine();             
		text = text.toUpperCase();//converting string into uppercase
 
		count = 0;
		System.out.print("Following characters are used in the input Text :");
		for ( ch = 'A'; ch <= 'Z'; ch++ )
		{
			int i; 
			for ( i = 0; i < text.length(); i++ ) //index in string
			{
				if ( ch == text.charAt(i) )
				{
					System.out.print(ch + " ");
					count++;
					break;
				}
			}
		}
		System.out.println("\nTotal Number of Different Characters : " + count);    
	}
}

Output

Enter the String : Hello World
Following characters are used in the input Text :D E H L O R W
Total Number of Different Characters : 7

Example Programs