Java Program to Count the Occurrences of Each Character
Last Updated :
09 Apr, 2025
In Java, counting the occurrences of each character in a string is a fundamental operation that can be done in different ways. This process involves identifying the frequency of each character in the input string and displaying it in a readable format.
Example: Input/output to count the occurrences of each character.
Input: s = “Geeks”
Output: G = 1, e = 2, k = 1, s=1.
Input: s = “Hello”
Output: H = 1, e= 1, l= 2, o= 1.
Naive Approach
This is the basic approach where, we manually compare each character of the string using nested loops and track the occurrences.
Algorithm:
- First, convert the string into an array of characters.
- Then, create a Boolean array of the same size as the input string with the characters.
- Iterate each character of the string one by one using a loop.
- If the character is counted, then make the boolean array at the same index as true ( The character is already counted ). Increment the count by 1.
- If the character is not counted then use another loop and compare it with the other characters of the string.
- After finishing the comparison, print the character occurrence count one by one.
Example: Iterative approach to counting the occurrences of each character in a String using nested loops.
Java
// Java program to count character occurrences
// using the Naive Approach
class Geeks{
public static void main(String[] args) {
String s = "Program";
char[] ch = s.toCharArray();
boolean[] b = new boolean[s.length()];
System.out.println("Character Occurrences:");
for (int i = 0; i < ch.length; i++) {
if (b[i]) continue; // Skip already counted characters
int c = 1;
for (int j = i + 1; j < ch.length; j++) {
if (ch[i] == ch[j]) {
c++;
b[j] = true; // Mark character as counted
}
}
System.out.println(ch[i] + " : " + c);
}
}
}
OutputCharacter Occurrences:
P : 1
r : 2
o : 1
g : 1
a : 1
m : 1
Explanation: The above example uses a “b” Boolean array to track counted characters. Then, nested loops iterate over the character array to calculate occurrences.
Other Methods to Count the Occurrences of Each Character
1. Using Counter Array
This method uses an integer array to store the frequency of characters based on their ASCII values.
Algorithm:
- First, create and integer array of size 256, which is used to store the ASCII values of the character.
- Now iterate through each character of the string one by one.
- Convert the character to it’s equivalent ASCII value.
- Now we use the ASCII value as index and we increament the count at that index if we found the character i.e for a = 97, arr[97] = arr[97]+1.
- After counting the frequency, print their count.
Example:
JAVA
// Java program to count character occurrences
// using Counter Array
class Geeks
{
public static void main(String[] args) {
String s = "Program";
int[] c = new int[256]; // Array for ASCII characters
// Increment count for each character
for (char ch : s.toCharArray()) {
c[ch]++;
}
System.out.println("Character Occurrences:");
// Print characters with non-zero counts
for (int i = 0; i < c.length; i++) {
if (c[i] > 0) {
System.out.println((char) i + " : " + c[i]);
}
}
}
}
OutputCharacter Occurrences:
P : 1
a : 1
g : 1
m : 1
o : 1
r : 2
Explanation: In the above example, the ASCII value of each character acts as the index in the counter
array. The program prints only non-zero counts by representing the character frequencies. This is efficient for ASCII characters but not suitable for Unicode.
2. Using Java HashMap
HashMap
is used to dynamically map each character to its count. This approach is suitable for both ASCII and Unicode characters.
Algorithm:
- Create a HashMap to store characters as key and value a their frequency.
- Iterate through each character of the string
- If the Character exists, increament its frequency.
- If it doesn’t exist, add it to the Map with initial frequency as 1.
- Then, print the each character with its frequencies.
Example:
Java
// Java program to count character occurrences
// using HashMap
import java.util.HashMap;
import java.util.Map;
class Geeks
{
public static void main(String[] args) {
String s = "Programming";
Map<Character, Integer> countMap = new HashMap<>();
for (char c : s.toCharArray()) {
countMap.put(c, countMap.getOrDefault(c, 0) + 1); // Update count
}
System.out.println("Character Occurrences:");
for (Map.Entry<Character, Integer> entry : countMap.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
}
OutputCharacter Occurrences:
P : 1
a : 1
r : 2
g : 2
i : 1
m : 2
n : 1
o : 1
Explanation: In the above example, the HashMap
stores characters as keys and their frequencies as values. The getOrDefault()
method simplifies updating the count for each character. This approach is efficient and works for both ASCII and Unicode strings.
3. Using Java 8 Streams
We can use Java 8, streams and collectors that provide a functional and concise way to count character occurrences.
Algorithm:
- Convert the String into a stream of characters using chars(), it returns IntStreasm of ASCII values.
- Use mapToobj() to convert the stream of integers to a stream of character object.
- Use Collectors.groupinBy() to group the characters and then use Collectors.counting() to count the occurrences of each character.
- Then,we store it in Map, where the key as is the character and frequency as its value.
Example:
Java
// Java program to count character occurrences
// using Java 8 Streams
import java.util.Map;
import java.util.stream.Collectors;
class Geeks
{
public static void main(String[] args) {
String s = "Programming";
Map<Character, Long> countMap = s.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(c -> c, Collectors.counting()));
System.out.println("Character Occurrences:");
countMap.forEach((k, v) -> System.out.println(k + " : " + v));
}
}
OutputCharacter Occurrences:
P : 1
a : 1
r : 2
g : 2
i : 1
m : 2
n : 1
o : 1
Explanation: In the above example, the chars()
method creates a stream of character codes from the string. The groupingBy
collector groups characters and counts their occurrences. This is a modern and concise solution but is the slightly slower due to stream overhead.
Similar Reads
Java program to count the occurrence of each character in a string using Hashmap
Given a string, the task is to write a program in Java which prints the number of occurrences of each character in a string. Examples: Input: str = "GeeksForGeeks" Output: r 1 s 2 e 4 F 1 G 2 k 2 o 1 Input: str = "Ajit" Output: A 1 t 1 i 1 j 1 An approach using frequency[] array has already been dis
2 min read
Count Occurrences of a Given Character using Regex in Java
Given a string and a character, the task is to make a function that counts the occurrence of the given character in the string using Regex. Examples: Input: str = "geeksforgeeks", c = 'e' Output: 4 'e' appears four times in str. Input: str = "abccdefgaa", c = 'a' Output: 3 'a' appears three times in
2 min read
Java program to count the characters in each word in a given sentence
Write a Java program to count the characters in each word in a given sentence? Examples: Input : geeks for geeksOutput :geeks->5for->3geeks->5 Recommended: Please solve it on PRACTICE first, before moving on to the solution. Approach:Here we have to find out number of words in a sentence an
3 min read
Java Program to Find Occurrence of a Word Using Regex
Java's regular expressions, or regex, let you do advanced text manipulation and matching. Regex offers a handy approach for searching for a term in a text wherever it appears. In this article, we will learn to find every occurrence of a word using regex. Program to Find Occurrence of a Word Using Re
2 min read
Java Program to Find the Occurrence of Words in a String using HashMap
HashMap<Key, Value> provides the basic implementation of the Map interface of Java and import java.util.HashMap package or its superclass. HashMap stores the data in (Key, Value) pairs, and accessed by an index of another type (e.g. an Integer). One object is used as a key to another object. I
3 min read
Java Program to Count Number of Digits in a String
The string is a sequence of characters. In java, objects of String are immutable. Immutable means that once an object is created, it's content can't change. Complete traversal in the string is required to find the total number of digits in a string. Examples: Input : string = "GeeksforGeeks password
2 min read
Java Program to Count Number of Vowels in a String
In java, the string is a sequence of characters and char is a single digit used to store variables. The char uses 2 bytes in java. In java, BufferedReader and InputStreamReader are used to read the input given by the user from the keyboard. Then readLine() is used for reading a line. The java.io pac
4 min read
Java program to print all duplicate characters in a string
Given a string, the task is to write Java program to print all the duplicate characters with their frequency Example: Input: str = "geeksforgeeks" Output: s : 2 e : 4 g : 2 k : 2 Input: str = "java" Output: a : 2 Approach: The idea is to do hashing using HashMap. Create a hashMap of type {char, int}
2 min read
Java Program to Check Whether the String Consists of Special Characters
In Java, special characters refer to symbols other than letters and digits, such as @, #, !, etc. To check whether the String consists of special characters, there are multiple ways, including using the Character class, regular expressions, or simple string checks. Example: In this example, we will
4 min read
How to Convert a String to a Character in Java?
String and char are fundamental and most commonly used datatypes in Java. A String is not a primitive data type like char. To convert a String to char in Java, we have to perform character-based operations or have to process individual characters. In this article, we will learn how to convert a Stri
3 min read