Program to find frequency of characters in a string in java

In this tutorial, we will see simple program to find frequency of characters in a string in java.
There are multiple ways to solve this proble. Let’s see one by one.
[toc]

Using counter array

Here is the algorithm for the same.

  • Initialize counter array of 256 length
  • Iterate over String and increase count by 1 at index based on Character. For example: If we encounter ‘a’ in String, it will be like counter[97]++ as ASCII value of ‘a’ is 97.
  • Iterate over counter array and print character and frequency if counter[i] is not 0.
import java.util.Scanner;

public class StringOperator
{
   public static void main(String args[])
   {
        int i;
        String str;

        int counter[] = new int[256];
        Scanner in = new Scanner(System.in);

        System.out.print("Enter a String : ");
        str=in.nextLine();

         for (i = 0; i < str.length(); i++) {
            counter[(int) str.charAt(i)]++;
        }
        // Print Frequency of characters
        for (i = 0; i < 256; i++) {
            if (counter[i] != 0) {
                  System.out.println("The character " + (char) i  + " has occurred for " + counter[i] + " times");
            }
        }
   }
}

Output:

Enter a String : Java2Blog
The character B has occurred for 1 times
The character J has occurred for 1 times
The character a has occurred for 2 times
The character g has occurred for 1 times
The character l has occurred for 1 times
The character o has occurred for 1 times
The character v has occurred for 1 times

Using HashMap

We can use HashMap as well to find Frequency of Each Character in a String.

  1. Create a HashMap which will contain character to count mapping.
  2. Iterate over String
  3. make count to 1 if HashMap do not contain the character and put it in HashMap with key as Character and count as value
  4. If HashMap already have the character, increment its count by 1
package org.arpit.java2blog;
import java.util.HashMap;
public class FindFrequencyCharMain {
   public static void main(String[] args) {
      String str = "java2blog";

      HashMap<Character,Integer> charFreqMap = new HashMap<>();
      for(int i= 0 ; i< str.length() ; i++) {
          Character ch=str.charAt(i);
         if(charFreqMap.containsKey(ch)) {
            int count = charFreqMap.get(ch);
            charFreqMap.put(ch,count+1);
         } else {
             charFreqMap.put(ch,1);
         }
      }
      System.out.println(charFreqMap);
   }
}

Output:

{a=2, 2=1, b=1, v=1, g=1, j=1, l=1, o=1}

Using HashMap's computeIfPresent and computeIfAbsent[java 8]

We can also use HashMap's computeIfPresent and computeIfAbsent to write code in more functional way. It uses Java 8's lambda expressions to write the logic.
Let's rewrite the code as below.

package org.arpit.java2blog;
import java.util.HashMap;
public class FindFrequencyCharMain {
   public static void main(String[] args) {
      String str = "java2blog";

      HashMap<Character,Integer> charFreqMap = new HashMap<>();
      for(int i= 0 ; i< str.length() ; i++) {
          Character ch=str.charAt(i);
          charFreqMap.computeIfPresent(ch, (character,count)-> count+1);
          charFreqMap.computeIfAbsent(ch, (character)-> 1);
      }
      System.out.println(charFreqMap);
   }
}

It will generate same output as above program.
That's all about program to find frequency of characters in a string in java.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.