Introduction
Finding the frequency of characters in a string is one of the most important beginner-level programming problems in Java. It helps developers understand concepts such as strings, loops, arrays, HashMap, character handling, and collections.
Character frequency means counting how many times each character appears in a given string.
For example:
Input String:
programming
Character Frequency:
p = 1
r = 2
o = 1
g = 2
a = 1
m = 2
i = 1
n = 1
Character frequency programs are commonly used in:
- Text analysis
- Data processing
- Search algorithms
- Duplicate character detection
- Anagram checking
- Compression algorithms
Java provides multiple ways to count character frequency, such as:
- Using loops and arrays
- Using HashMap
- Using Java Streams
In this tutorial, you will learn how to write a Java program to count character frequency, understand different approaches, analyze complexity, learn common mistakes, and prepare for Java interview questions.
What is Character Frequency?
Character Frequency refers to the number of times a particular character appears in a string.
Example:
String:
hello java
Frequency:
h → 1
e → 1
l → 2
o → 1
(space) → 1
j → 1
a → 2
v → 1
Here:
- Character l appears 2 times.
- Character a appears 2 times.
- Other characters appear only once.
Syntax
The basic syntax to count character frequency:
HashMap map = new HashMap<>();
for(char ch : text.toCharArray()) {
map.put(ch, map.getOrDefault(ch, 0) + 1);
}
Java Character Frequency Program Using HashMap
import java.util.HashMap;
import java.util.Map;
public class CharacterFrequency {
public static void main(String[] args) {
String text = "programming";
HashMap frequency = new HashMap<>();
for(char ch : text.toCharArray()) {
frequency.put(ch, frequency.getOrDefault(ch, 0) + 1);
}
System.out.println("Character Frequency:");
for(Map.Entry entry : frequency.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
}
}
Output
p = 1
r = 2
o = 1
g = 2
a = 1
m = 2
i = 1
n = 1
Explanation of the Program
Step 1: Create a String
String text = "programming";
This string contains characters whose frequency needs to be calculated.
Step 2: Create HashMap
HashMap frequency = new HashMap<>();
The HashMap stores:
Character as a key
Count as a value
Example:
r → 2
g → 2
m → 2
Step 3: Convert String into Character Array
text.toCharArray()
This converts:
programming
into:
p r o g r a m m i n g
Step 4: Count Characters
frequency.put(ch, frequency.getOrDefault(ch, 0) + 1);
This statement works as:
First occurrence:
g → 1
Second occurrence:
g → 2
Step 5: Display Frequency
for(Map.Entry entry : frequency.entrySet())
This loop displays every character and its count.
Java Character Frequency Program Using User Input
import java.util.HashMap;
import java.util.Scanner;
public class CharacterFrequency {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String text = scanner.nextLine();
HashMap frequency = new HashMap<>();
for(char ch : text.toCharArray()) {
frequency.put(ch, frequency.getOrDefault(ch, 0) + 1);
}
System.out.println("Character Frequency:");
for(char ch : frequency.keySet()) {
System.out.println(ch + " = " + frequency.get(ch));
}
scanner.close();
}
}
Output
Java Programming
Character Frequency:
J = 1
a = 3
v = 1
P = 1
r = 2
o = 1
g = 2
m = 2
i = 1
n = 1
Java Character Frequency Using Array
Since characters have numeric ASCII values, we can also use an array.
public class CharacterFrequency {
public static void main(String[] args) {
String text = "hello";
int[] frequency = new int[256];
for(int i = 0; i < text.length(); i++) {
frequency[text.charAt(i)]++;
}
System.out.println("Character Frequency:");
for(int i = 0; i < frequency.length; i++) {
if(frequency[i] > 0) {
System.out.println((char)i + " = " + frequency[i]);
}
}
}
}
Output
h = 1
e = 1
l = 2
o = 1
Java Character Frequency Without Considering Spaces
Sometimes spaces are not counted.
Example:
Input:
hello java
Output
e = 1
l = 2
o = 1
j = 1
a = 2
v = 1
Program:
import java.util.HashMap;
public class CharacterFrequency {
public static void main(String[] args) {
String text = "hello java";
HashMap frequency = new HashMap<>();
for(char ch : text.toCharArray()) {
if(ch != ' ') {
frequency.put(ch, frequency.getOrDefault(ch, 0) + 1);
}
}
System.out.println(frequency);
}
}
Algorithm
- Start the program.
- Read a string.
- Create a storage structure for characters and counts.
- Traverse each character of the string.
- Check whether the character already exists.
- Increase the count if it exists.
- Add the character with count 1 if it does not exist.
- Display character frequencies.
- End the program.
Flowchart
Start
|
|
Read String
|
|
Create Frequency Map
|
|
Read Each Character
|
|
Character Exists?
|
Yes No
| |
Increase Add Character
Count With Count 1
|
Next Character
|
Display Frequency
|
End
Time Complexity
If the string length is n:
Time Complexity = O(n)
Explanation:
The program checks every character only once.
Example:
For:
programming
The program processes 11 characters.
Space Complexity
Using HashMap:
Space Complexity = O(n)
Because the map stores each unique character.
Using Array:
Space Complexity = O(1)
Because the size of the character array is fixed.
Advantages of Character Frequency Program
- Easy to understand.
- Helps learn HashMap.
- Useful for string analysis.
- Used in many interview problems.
- Improves understanding of data structures.
Disadvantages
- HashMap requires additional memory.
- Case-sensitive comparison may create separate entries.
Example:
A, a are treated as different characters.
- Large Unicode text may require special handling.
Common Mistakes
1. Forgetting Character Case
Example:
Java
JAVA
Uppercase and lowercase are different.
Solution:
Convert string to lowercase:
text = text.toLowerCase();
2. Counting Spaces Accidentally
Input:
hello java
Space may be counted as a character.
Solution:
if(ch != ' ')
3. Using Wrong HashMap Type
Incorrect:
HashMap<String,Integer>
Correct:
HashMap<Character,Integer>
Because individual characters are stored.
4. Forgetting Initial Value
Incorrect:
map.put(ch, count + 1);
Correct:
map.put(ch, map.getOrDefault(ch,0)+1);
5. Modifying String While Counting
Strings are immutable in Java. Avoid changing the original string during processing.
Real-Life Applications
Character frequency counting is used in:
Text Analysis
Analyzing documents and articles.
Example:
- Most common letters
- Word patterns
Password Validation
Checking character distribution in passwords.
Data Compression
Algorithms like Huffman Coding use character frequency.
Search Engines
Analyzing text content and keywords.
Anagram Checking
Two strings are anagrams if their character frequencies match.
Example:
listen
silent
Both have the same character frequency.
Summary
The Java Character Frequency Program is an important string programming concept that helps developers understand how to count and analyze characters in a string.
Using HashMap is the most common and efficient approach because it provides simple frequency storage and retrieval. The concept is widely used in real-world applications such as text processing, data compression, password validation, and anagram checking.