Java Program to Count the Occurrence of Each Character in String

« Java Tutorial Java Examples »

This article is created to cover a program in Java, to count the occurrence of each character in a string entered by user at run-time of the program.

The question is, write a Java program to count and print the occurrence of each characters available in a string. The string must be received by user at run-time. The program given below is its answer:

import java.util.Scanner;

public class CodesCracker
   public static void main(String[] args)
      int len, i, k, count, prevLen, arri=0, arrLen=0;
      String str;
      char ch;
      Scanner s = new Scanner(;
      System.out.print("Enter the String: ");
      str = s.nextLine();
      len = str.length();
      char[][] arr = new char[len][2];
      for(i=0; i<len; i++)
         ch = str.charAt(i);
         count = 0;
         for(k=0; k<arrLen; k++)
               prevLen = (arr[k][1]);
               prevLen = prevLen+1;
               arr[k][1] = (char)prevLen;
            arr[arri][0] = ch;
            arr[arri][1] = '1';
      for(i=0; i<arrLen; i++)
         System.out.println(arr[i][0]+ " -> " +arr[i][1]);

Here is its sample run with user input codescracker as string to count occurrence of each character available in this given string:

java count occurrence of each character in string

Here is another sample run with user input, Welcome to

count occurrence of each character in string java

In above sample output, in between the character m and t, the occurrence 2 refers to white space.

In above program, I've created a two dimensional array. That is, array inside array. The inner array is of size 2. Where at the first index, I've placed the character, and at second, I've placed its occurrence. And the whole array of character and its occurrence, is wrapped in an outer array of size equals to the total number of unique characters, available in given string.

Note - Since the array arr is of char data type, therefore before initializing the value of prevLen (an int type variable), we need to typecast the variable into char. So I've done using (char)prevLen.

The dry run of above program with user input codescracker goes like:

Java Online Test

« Java Tutorial Java Examples »

© Copyright 2021. All Rights Reserved.