Java Program to Count Frequency of Character in String ( 4 Methods )

By | 16.03.2017

Java Program to Count Frequency of Character in String

Write a Java Program to Count Frequency of Character in String. Here’s a Simple Program To Count Frequency of Character in String in Java Programming Language.

Since there’s no pre-build function present in Java for calculating the occurrence of the characters or alphabets. Hence we need to implement our own logic to Count Frequency of Character in a String. Here we will see four different methods of solving the problem.

What are Strings?

String is basically a sequence of Characters. String is a Class provided in Java Library Files which are used to manipulate the Strings. In C Programming, String was an Array of Characters but here the case is bit different.


1. Start

2. Accept a string from the user.

3.Accept a character from the user which u want to search.

4. Count the no. of times it occurs in the string.

5. Print its frequency.

6. End

Following Java Program ask to the user to enter a string and character to find the frequency of character present in the string and display the frequency of character on the screen.

Below is the source code for Java Program to Count no of occurrences of Character in String which is successfully compiled and run on Windows System to produce desired output as shown below :

1. Using replaceAll( ) and length( ) in Strings(Java) :


2. Using Simple for loop in Java : :


import java.util.Scanner;
public class Count_Occurrance {

     public static void main(String[] args) {
        Scanner sc = new Scanner(;
        System.out.print("Enter any String : ");
        String s =;
        System.out.print("Enter a character to count in [" + s + "] : ");
        char c =".").toLowerCase().charAt(0);
        int cn = 0;
        for (int i = 0; i < s.length(); i++) {
            if (c == s.charAt(i)) {
        System.out.println(c + " occurs " + cn + " times in " + s);


Enter any String : CodezClub
Enter a character to count in [codezclub] : o
o occurs 1 times in codezclub


3. Using Enhanced for loop in String(Java): :

4. Using Recursion in Java : :

5 1 vote
Article Rating
Category: Java Programming String Programs Tags:

About Tunde A

My name is Tunde Ajetomobi, a Tech Enthusiast and Growth Hacker. I enjoy creating helpful content that solves problem across different topics. Codezclub is my way of helping young aspiring programmers and students to hone their skills and find solutions on fundamental programming languages.

Notify of

1 Comment
Newest Most Voted
Inline Feedbacks
View all comments

Can you please change the color of code to white in dark mode?
Its hard to read ..