Count Frequency of Each Character in a String in Java
Counting the frequency of each character means finding how many times every character appears in a string. This is one of the most important string problems and forms the base for many advanced problems like anagrams, duplicates, and compression.
Character frequency counting is commonly used in:
- Text analysis
- Search engines
- Data validation
How the Logic Works
- Create an array to store frequency of characters.
- Traverse the string character by character.
- Increase count for each character.
- Print characters with their frequency.
Example 1
Input: "programming"
- p → 1
- r → 2
- o → 1
- g → 2
- m → 2
- a → 1
- i → 1
- n → 1
Example 2
Input: "Java"
- j → 1
- a → 2
- v → 1
Java Program to Count Frequency of Each Character
import java.util.Scanner;
public class CharacterFrequency {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine().toLowerCase();
int[] freq = new int[256];
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch != ' ') {
freq[ch]++;
}
}
System.out.println("Character Frequencies:");
for (int i = 0; i < 256; i++) {
if (freq[i] > 0) {
System.out.println((char) i + " -> " + freq[i]);
}
}
}
}
Sample Output
Enter a string: success
Character Frequencies:
s -> 3
u -> 1
c -> 2
e -> 1
Important Notes
- Spaces are ignored.
- Program is case-insensitive.
- Uses ASCII-based frequency array.
Practice Challenges
- Count frequency using HashMap instead of array.
- Print frequencies in sorted order.
- Count frequency of words instead of characters.
Character frequency counting is a foundational skill for mastering string manipulation problems in Java.