Frequency of Characters

Count frequency of each character in a string.

IntermediateTopic: Module 4: String Programs
Back

Java Frequency of Characters Program

This program helps you to learn the fundamental structure and syntax of Java programming.

Try This Code
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String s = sc.nextLine();

        Map<Character, Integer> freq = new LinkedHashMap<>();
        for (char c : s.toCharArray()) {
            freq.put(c, freq.getOrDefault(c, 0) + 1);
        }

        for (Map.Entry<Character, Integer> e : freq.entrySet()) {
            System.out.println(e.getKey() + " -> " + e.getValue());
        }
        sc.close();
    }
}
Output
Enter a string: aabccc
a -> 2
b -> 1
c -> 3

Understanding Frequency of Characters

We use a LinkedHashMap to keep counts in the order of first appearance.

Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.

Table of Contents