Java program to check frequency of characters in a string

Check Frequency of Characters in a string

Finding the frequency of a character in a string, means we have to check how many times a particular character is present in that string. Here, we have coded a Java Program for the same. Let’s take an example of a string “prepinsta” . In which we have to check that how many times each of the characters gets repeated in the string.


Java program to check frequency of characters in a string


  •  Take string input from user and store it in the variable called “str”.
  • After that make freq array having size of length of string.
  • Convert string to char array .
  • Run for loop start from i=0 to str<length() store 1 to freq array.
  • Run j loop start from i=i+1 to j<str.length().
  • check condition if(string[i] == string[j]) then do freq[i]++  and set string[j]=’0′ .
  • After that display frequency of character one by one.

Code in Java (Check Frequency of Characters)

import java.util.Scanner;

public class FrequencyOfCharactersInAString {
   public static void main(String[] args) {
    Scanner sc =new Scanner(;
     System.out.print("Enter String : ");
     String str = sc.nextLine(); 
     int[] freq = new int[str.length()]; 
     int i, j; 

     //Converts given string into character array 
     char string[] = str.toCharArray(); 
     for(i = 0; i <str.length(); i++) { 
        freq[i] = 1; 
          for(j = i+1; j <str.length(); j++) { 
            if(string[i] == string[j]) { 

           //Set string[j] to 0 to avoid printing visited character 
            string[j] = '0'; 
    //Displays the each character and their corresponding frequency 
    System.out.println("Characters and their corresponding frequencies"); 
    for(i = 0; i <freq.length; i++) { 
       if(string[i] != ' ' && string[i] != '0') 
          System.out.println(string[i] + "-" + freq[i]); 


Enter String : prepinsta
Characters and their corresponding frequencies

One comment on “Java program to check frequency of characters in a string”

  • Mahesh

    import java.util.*;
    public class Main
    public static void main(String[] args) {
    String s=”prepinsta”;
    Mapmap=new HashMap();
    for(int i=0;i “+entry.getValue()+” “);