Table of contents
1.
Introduction
2.
Naive Approach
3.
Algorithm
3.1.
Stages of the Algorithm
3.2.
What is the point in using an algorithm?
3.3.
When should we use this Algorithm?
4.
Example
4.1.
Step-by-Step Execution
4.2.
Code Example
4.3.
Key Points to Remember:
5.
Other Methods to Count Character Occurrences
5.1.
1. Using Counter Array
5.2.
2. Using Java HashMap
5.3.
3. Using Java 8 Streams
6.
To Which Method and When?
7.
Frequently Asked Questions
7.1.
What is case-sensitive counting and case-insensitive counting?
7.2.
What is the most efficient method for large texts?
7.3.
How would I get the count of all characters, and not only one?
8.
Conclusion
Last Updated: Jun 22, 2025
Easy

Occurrence of Character in String in Java

Author Gaurav Gandhi
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

String handling is an essential concept in Java programming. Count the number of occurrences of a particular character in a string is one of the standard tasks. This is operation is applied in data validation, cryptography, and text processing. 

Occurrence of Character in String in Java

In this article, we are going to discuss various methods of counting character incidences in Java.  We will begin with an easy solution, talk about effective algorithms, and later on, more complicated ones such as the application of arrays, HashMaps, and Java 8 Streams.

Naive Approach

The easiest solution to the number of times a character is present in a string would be to loop each character and check whether it is equal to the target character. It is dubbed Naive Approach, since no sophisticated structures of data or optimizations are applied here--only simple iteration.

How This Works
 

  • Use a string (ex: hello) and a target character (ex, l).
     
  • Set a count to zero (count = 0).
     
  • Iterate through every char in the string.
     
  • In case the current character is similar to the target, turn the counter up 1.
     
  • Upon terminating the loop, the counter contains the count of total occurrences.

For Example:

public class Main {
    public static void main(String[] args) {
        String str = "programming";
        char target = 'm';
        int count = 0;

        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == target) {
                count++;
            }
        }


        System.out.println("The character '" + target + "' appears " + count + " times.");
    }
}
You can also try this code with Online Java Compiler
Run Code


Output:

The character 'm' appears 2 times.


In this code:

  • We use a for loop to check each character (str.charAt(i)).
     
  • If the character matches target, we increase count by 1.
     
  • Finally, we print the result.

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

  1. String: "Mississippi"
     
  2. Target character: 's'
     
  3. Initialize counter: count = 0
     

Now, let's go through each character:

  1. First character 'M' → Not 's' → count stays 0
     
  2. Second character 'i' → Not 's' → count stays 0
     
  3. Third character 's' → Match! → count becomes 1
     
  4. Fourth character 's' → Match! → count becomes 2
     
  5. Fifth character 'i' → Not 's' → count stays 2
     
  6. Sixth character 's' → Match! → count becomes 3
     
  7. Seventh character 's' → Match! → count becomes 4
     
  8. Eighth character 'i' → Not 's' → count stays 4
     
  9. Ninth character 'p' → Not 's' → count stays 4
     
  10. Tenth character 'p' → Not 's' → count stays 4
     
  11. 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:
 

  1. Very fast for simple cases
     
  2. Easy to understand
     

Cons:

  1. Wastes memory (we create 256 spaces but use only a few)
     
  2. 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:
 

  1. Works for any character type
     
  2. Only stores characters that actually appear
     
  3. Very efficient for large texts
     

Cons:
 

  1. Slightly more complex to understand
     
  2. 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:

  1. Very clean and modern code
     
  2. Easy to read once you understand streams
     
  3. Powerful for more complex operations

Cons:

  1. Requires Java 8 or higher
     
  2. 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. 

Live masterclass