0
0
JavaHow-ToBeginner · 3 min read

How to Count Occurrences of a Character in a String in Java

To count occurrences of a character in a string in Java, you can loop through the string and compare each character with the target using charAt(). Increment a counter each time you find a match. Alternatively, use Java 8 streams with chars() and filter() to count matches.
📐

Syntax

Use a loop to check each character in the string with charAt(index). Increase a counter when the character matches the target.

Alternatively, use Java 8 streams: convert the string to an IntStream of characters with chars(), then filter and count matches.

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

// Using streams (Java 8+)
long count = str.chars().filter(ch -> ch == targetChar).count();
💻

Example

This example shows how to count the number of times the character 'a' appears in the string "banana" using both a loop and Java streams.

java
public class CountChar {
    public static void main(String[] args) {
        String str = "banana";
        char targetChar = 'a';

        // Using loop
        int countLoop = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == targetChar) {
                countLoop++;
            }
        }

        // Using streams
        long countStream = str.chars().filter(ch -> ch == targetChar).count();

        System.out.println("Count using loop: " + countLoop);
        System.out.println("Count using streams: " + countStream);
    }
}
Output
Count using loop: 3 Count using streams: 3
⚠️

Common Pitfalls

  • Using == to compare strings instead of characters causes errors; always compare characters with charAt().
  • Not handling empty strings or null values can cause exceptions.
  • Counting substrings instead of single characters requires different logic.
java
/* Wrong: comparing strings instead of chars */
String str = "apple";
int count = 0;
for (int i = 0; i < str.length(); i++) {
    // Incorrect: comparing String to char
    if (str.substring(i, i+1).equals("a")) {
        count++;
    }
}

/* Right: compare chars */
for (int i = 0; i < str.length(); i++) {
    if (str.charAt(i) == 'a') {
        count++;
    }
}
📊

Quick Reference

Counting character occurrences in Java:

  • Use charAt(index) to get each character.
  • Compare with target character using ==.
  • Increment a counter for each match.
  • Java 8+: Use str.chars().filter(ch -> ch == targetChar).count() for concise code.

Key Takeaways

Use a loop with charAt() to check each character and count matches.
Java 8 streams provide a concise way to count characters with chars() and filter().
Always compare characters with '==' not strings with '=='.
Handle empty or null strings to avoid errors.
Counting substrings requires different methods than counting single characters.