Home Java Programming Language / Programs / Write a program to input a string in uppercase and print the frequency of each character.
🚀 Programming Example

Write a program to input a string in uppercase and print the frequency of each character.

👁 185 Views
💻 Practical Program
📘 Step Learning
Learn this program step-by-step with algorithm, source code, output and detailed explanation.

📌 Information & Algorithm

Write a program to input a string in uppercase and print the frequency of each character.

Example:

Input: COMPUTER HARDWARE

Output:

CHARACTERS   FREQUENCY
A            2
C            1
D            1
E            2
H            1
M            1
O            2
P            1
R            2
T            1
U            1
W            1

💻 Program Code

import java.io.*;

class Frequency {
    String s;
    int i, j, l, f;

    void display() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter a string in upper case:");
        s = br.readLine();
        l = s.length();

        System.out.println("CHARACTERS   FREQUENCY");
        for (i = 65; i <= 90; i++) { // ASCII values for 'A' to 'Z'
            f = 0;
            for (j = 0; j < l; j++) {
                if (s.charAt(j) == i) {
                    f++;
                }
            }
            if (f > 0) {
                System.out.println((char)i + "\t\t" + f);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        Frequency freq = new Frequency();
        freq.display();
    }
}

                        

📘 Explanation

Variable Table

Variable Type Description
s String To store the input string.
i int Loop variable for ASCII values from 65 ('A') to 90 ('Z').
j int Loop variable for iterating through the string.
l int To store the length of the input string.
f int To store the frequency of each character.

This program counts and prints the frequency of each character in the input string, considering only uppercase letters.

📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.