</>

Technology

Java Programs

Difficulty

Beginner

Interview Question

Write a Java program to count the number of occurrences of a character in a string.

Answer

Count Character Occurrences in a String

Java
public class CountCharacterOccurence {
    public static void main(String[] args) {
        String s = "Java is java again java again";
        char c = 'a';

        // Count using replace technique
        int count = s.length() - s.replace("a", "").length();

        System.out.println("Number of occurances of 'a' is: " + count);  // → 10
    }
}

Output

CODE
Number of occurances of 'a' is: 10

How the Replace Technique Works

CODE
Original string: "Java is java again java again"  length = 29
After removing 'a': "Jv is jv gin jv gin"         length = 19
Difference: 29 - 19 = 10  → 10 occurrences of 'a'

Alternative: Loop with charAt()

Java
public class CountCharLoop {
    public static void main(String[] args) {
        String s = "Java is java again java again";
        char target = 'a';
        int count = 0;

        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == target) {
                count++;
            }
        }
        System.out.println("Count of '" + target + "': " + count);  // → 10
    }
}

Case-Insensitive Count

Java
String s = "Java is Java again";
char target = 'j';  // count both 'j' and 'J'

long count = s.toLowerCase()
              .chars()
              .filter(ch -> ch == Character.toLowerCase(target))
              .count();

System.out.println("Case-insensitive count: " + count);  // → 2

Count All Characters (Frequency Map)

Java
import java.util.HashMap;
import java.util.Map;

String s = "automation";
Map<Character, Integer> freq = new HashMap<>();

for (char ch : s.toCharArray()) {
    freq.put(ch, freq.getOrDefault(ch, 0) + 1);
}

System.out.println(freq);
// {a=3, u=1, t=2, o=2, i=1, n=1, m=1}

Automation Testing Relevance

Java
// Verify a field contains exactly N special characters
String password = driver.findElement(By.id("password")).getAttribute("value");
int specialCount = password.length() - password.replace("@", "").length();
assertTrue(specialCount >= 1, "Password must contain at least one @");

Follow AutomateQA