Algorithm
Algorithm is simply a text-based procedure of doing something. To count the characters in a string we can set a clear algorithm on the naive one we have just now seen.
Stages of the Algorithm
- Start: Start with the string to be entered, and chosen character.
- Initialize- reset a counter to 0.
- Loop- Increment the character of the string.
- Check - in case the immediate character = the one intended, add to the count.
- Finish- Once the verification of all characters has been done, the count value is returned.
What is the point in using an algorithm?
- It assists in planning the thoughts prior to writing the code.
- Allows describing the logic to others more easily.
- It can be made efficient at a later stage.
- Instead of getting it in abstract words, let us learn it with an example:
Imagine that we have:
String: "banana"
Character to be targeted: a
The functioning of the algorithm:
1. Start with count = 0.
2. Check each letter:
- 'b' → Not 'a' → count stays 0.
- 'a' → Match → count becomes 1.
- 'n' → Not 'a' → count stays 1.
- 'a' → Match → count becomes 2.
- 'n' → Not 'a' → count stays 2.
- 'a' → Match → count becomes 3.
3. Final answer: there are three occurrences of a.
When should we use this Algorithm?
Suitable with small strings, or basic programs.
Not the quickest when very long strings are taken (we shall meet improved methods to-wards the end of the chapter).
Example
Let's take a real example to see how character counting works in practice. We'll use the word "Mississippi" and count how many times the letter 's' appears.
Step-by-Step Execution
- String: "Mississippi"
- Target character: 's'
- Initialize counter: count = 0
Now, let's go through each character:
- First character 'M' → Not 's' → count stays 0
- Second character 'i' → Not 's' → count stays 0
- Third character 's' → Match! → count becomes 1
- Fourth character 's' → Match! → count becomes 2
- Fifth character 'i' → Not 's' → count stays 2
- Sixth character 's' → Match! → count becomes 3
- Seventh character 's' → Match! → count becomes 4
- Eighth character 'i' → Not 's' → count stays 4
- Ninth character 'p' → Not 's' → count stays 4
- Tenth character 'p' → Not 's' → count stays 4
- Eleventh character 'i' → Not 's' → count stays 4
Final Result: The letter 's' appears 4 times in "Mississippi".
Code Example
public class CountCharacterExample {
public static void main(String[] args) {
String word = "Mississippi";
char target = 's';
int count = 0;
for(int i = 0; i < word.length(); i++) {
if(word.charAt(i) == target) {
count++;
}
}
System.out.println("The letter 's' appears " + count + " times.");
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
The letter 's' appears 4 times.
Key Points to Remember:
- The loop checks every single character in the string.
- The comparison is case-sensitive ('S' and 's' are different in Java).
- This method works for any string and any character you want to count.
Other Methods to Count Character Occurrences
While the naive approach works fine, Java gives us several smarter ways to count characters. Let's look at three better methods:
1. Using Counter Array
This method is faster than the naive approach and works well for simple cases.
How it works:
- We create an array of size 256 (to cover all ASCII characters)
- Each array position represents one character
- We increment the count at the character's position
public class ArrayCounter {
public static void main(String[] args) {
String text = "hello world";
int[] counts = new int[256]; // Covers all ASCII characters
for(int i=0; i<text.length(); i++) {
char c = text.charAt(i);
counts[c]++;
}
// Print count for 'l'
System.out.println("'l' appears " + counts['l'] + " times");
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
'l' appears 3 times
Pros:
- Very fast for simple cases
- Easy to understand
Cons:
- Wastes memory (we create 256 spaces but use only a few)
- Only works for ASCII characters
2. Using Java HashMap
This is more efficient and works for any Unicode character.
import java.util.HashMap;
public class HashMapCounter {
public static void main(String[] args) {
String text = "programming";
HashMap<Character, Integer> counts = new HashMap<>();
for(char c : text.toCharArray()) {
counts.put(c, counts.getOrDefault(c, 0) + 1);
}
System.out.println("Counts: " + counts);
System.out.println("'m' appears " + counts.get('m') + " times");
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
Counts: {p=1, r=2, a=1, g=2, m=2, i=1, n=1, o=1}
'm' appears 2 times
Pros:
- Works for any character type
- Only stores characters that actually appear
- Very efficient for large texts
Cons:
- Slightly more complex to understand
- Uses more memory than array for small cases
3. Using Java 8 Streams
This is the most modern approach, using Java's stream API.
import java.util.Map;
import java.util.stream.Collectors;
public class StreamCounter {
public static void main(String[] args) {
String text = "java programming";
Map<Character, Long> counts = text.chars()
.mapToObj(c -> (char)c)
.collect(Collectors.groupingBy(c -> c, Collectors.counting()));
System.out.println("Counts: " + counts);
System.out.println("'a' appears " + counts.get('a') + " times");
}
}

You can also try this code with Online Java Compiler
Run Code
Output:
Counts: { =1, a=3, r=2, g=2, i=1, j=1, m=2, n=1, o=1, p=1, v=1}
'a' appears 3 times
Pros:
- Very clean and modern code
- Easy to read once you understand streams
- Powerful for more complex operations
Cons:
- Requires Java 8 or higher
- To the newcomers, streams may be confusing
To Which Method and When?
Naive approach: Naive approach is used when learning or when extremely simple programs are involved
- Counter array: A counter array is used when dealing with ASCII alone, and speed is a factor
- HashMap: In the majority of real-world applications
- Streams: In a situation of writing contemporary Java code, and require readability is required
Frequently Asked Questions
What is case-sensitive counting and case-insensitive counting?
Case-sensitive counting means that both A and a are distinct characters (which happens by default in Java). In case-insensitive counting, lowercase the string after which a count is done with the help of text.toLowerCase().
What is the most efficient method for large texts?
In large texts, the HashMap approach is usually optimal since it uses minimal memory, avoiding writing those characters that will never be used, and is fast. The array approach may be faster yet inefficient in the use of memory.
How would I get the count of all characters, and not only one?
Each of these approaches will automatically count all the characters. In these HashMap and Stream examples, we are already making whole counts of characters; we simply demonstrated how to obtain the count of one character to make it easy.
Conclusion
In this article, we have come to know of a few methods to count the occurrence of characters in a Java string. The first thing we had was a very naive implementation, which we solved with a loop, then we checked more efficient ways, using a counter array, a HashMap, and Java 8 Streams. Every technique has advantages - the naive technique is ideal when learning, HashMaps are best suited to most real programs, and Streams give clean, modern code. We have also been shown how to deal with various requirements, such as case sensitivity. Now you are in the position to solve any character-counting problem within your Java programs using these techniques.