×

Java program to find frequency of characters in a string

In this article, you will understand the how to find the frequency of characters in strings by using Java programming language. Along with this, you will understand the hashing concept in java (Hash map).

Problem description

You have given a string, and you must find out the frequency of each character in the string and print them.

You need to write a java program for the above problem.

Solution

Approach-1: This problem can be done using hashing technique. You can use the hash map. You need to pass character as key record and integer as value record while creating a hash map. Now the logic is you must store the characters of the given string in the key record. And need to store the count of each character of the string in their respective key-value record. If you encounter the character again, you need to increment the frequency count of that character in the hash map. Finally, you need to traverse the hash map and print the character along with its count values.

Program

import java.io.*;
import java.util.*;
import java.lang.*;
public class Main
{
public static void main(String[] args) {
Scanner sc=new Scanner (System.in);
                      System.out.println(“Please enter the String:”);
String repString=sc.next();
FreqString StringFreq=new FreqString();
     StringFreq.Frequency(repString);
}
}
class FreqString
{
    void Frequency(String s)
    {
        HashMap<Character,Integer> Freq=new HashMap<>();
        for(int i=0;i<s.length();i++)
        {
            if(Freq.containsKey(s.charAt(i)))
            {
                Freq.put(s.charAt(i),Freq.get(s.charAt(i))+1);
            }
            else
            {
                Freq.put(s.charAt(i),1);
                
            }
        }
        
        for(int i=0;i<s.length();i++)
        {
            if(Freq.get(s.charAt(i))!=0)
            {
                System.out.println(s.charAt(i)+"->"+Freq.get(s.charAt(i)));
                Freq.put(s.charAt(i),0);
            }
        }
    }
}

Output

Java program to find the frequency of characters in a string

Time complexity: O(n), n is the length of string input.

Space: O(n).

Approach-2: This is a brute force approach where you will take an array to store the frequency of each character in the string. You will need to compare every character of the string with each other.

Generally, this is the brute force approach that one can follow to solve the problem.

The time complexity of this approach is O(n^2) in the worst case. And space complexity is O(1).

Program

import java.io.*;
import java.util.*;
import java.lang.*;
public class Main
{
public static void main ( String [] args) {
Scanner sc=new Scanner ( System.in);
String repString = sc.next ();
FreqString StringFreq = new FreqString ();
     StringFreq.Frequency( repString );
}
}
class FreqString
{
    void Frequency( String s )
    {
        int [] freq = new int[s.length()];  
        char[] str = s.toCharArray();
        for(int i= 0 ; i < s.length () ; i++)
        {
            int c = 1;
            for (int j = i+1; j < s.length(); j++)
            {
                if ( str[i] == str[j] )
                {
                    c++;
                    str[j] = '0';
                }
            }
            freq[i] = c;
        } 
        for(int i =0;  i < freq.length ;i++)
        {
            if(str[i] !=' ' &&  str[i] !='0')
            {
                System.out.println ( str[i] +" -> " + freq[i]);
            }
        }
    }
}

Output

Java program to find the frequency of characters in a string

If you want to perform any operation on a string, then you need to understand the concept of mutable and immutable.

Strings are immutable. You cannot directly change the values in the string, that is, adding or removing any values from the string. To perform this kind of operation then, you need to convert the string into another mutable data type.

So, you need to use type conversion to change the string data type into another data type. You need to change the string data type to char array to perform the addition or removal of characters from the string.

In the above program, if you try to compare each character of the string with others, then you will get an error, but if you convert the string to an array type, then you can perform these operations.

In a programming language, the term mutable refers to the feasibility of a data type or data structure to change its values during the run time. Or simply if we can change the values of a component during the run time execution, then we say that component is mutable.

Ex: list, sets, arrays etc.

While coming to the concept of immutable, if we are unable to change the values of a component during the run time of a program, then we classify those components into immutable contents.

Ex: Strings.


Related Topics

Java Math nextAfter() Method

The nextAfter() method of Math class returns the floating-point value adjacent to the first argument in direction of the second argument. Syntax: public static double nextAfter (double start, double direction)public static float...

2 minutes read.

Hourglass problem in Java

In this section, we will discuss the hourglass problem in Java.The aim is to find the largest sum of an hour glass given a 2D matrix. An hour glass is made...

2 minutes read.

Java program to find frequency of characters in a string

In this article, you will understand the how to find the frequency of characters in strings by using Java programming language. Along with this, you will understand the hashing concept...

3 minutes read.

Java 8 Multimap

Java comes with several practical built-in collection libraries. However, there are situations when we need specialized collections that are not included in the Java standard library. The Multimap is one...

7 minutes read.

How to Read XML Files in Java?

Introduction Today, we are going to learn about how to read XML files in java. Before, reading the XML Files let us learn about XML. XML Files The full form of XML is...

8 minutes read.

How to Print array in Java?

A Java array is a data structure that allows us to hold components of the same data type. An array's items are kept in a single memory region. As a...

6 minutes read.

Java LinkedHashSet

LinkedHashSet in Java with Example Java LinkedHashSet extends HashSet and Implements the Set interface. It doesn’t contain only duplicate values like HashSet. It also permits the null elements. It maintains the order...

5 minutes read.

Prime Points in Java

The points that divide an integer into two halves containing a prime number are known as prime points. Printing every prime point of a specific number is the task. Let's...

6 minutes read.

Java HashSet

HashSet implements the set interface. It uses the hash table to make the collection to store different data types. The hash set is the unordered collection of different data types....

6 minutes read.

Trim Method in String Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

3 minutes read.

Java concurrency interview questions

During technical interviews, one of the most challenging and sophisticated subjects is concurrency in Java. This page offers responses to some of the related interview questions you might come across. 1....

11 minutes read.

Difference Between Access Specifiers and Modifiers in Java

Java employs access modifiers to restrict a class's data members, member functions, and constructor. Access modifiers are essential when creating Java program and applications. Access modifiers in Java include: defaultpublicprotectedprivate Default Access Modifiers Without...

4 minutes read.

Java Implements Keyword

To understand about the keyword implements we need to learn about the concept of the interfaces and inheritance in java programming languages. So let us learn about the interface and...

3 minutes read.

Reverse a String in Java

Reversing a string means that if we have a string called “what is your name”, the reversed format is “eman ruoy si tahw”. Reversing a string involves totally flipping the...

3 minutes read.

Swing Program in Java

Java Swing is part of Java Foundation Classes (JFC). The swing toolkit is used to generate Graphical User Interface (GUI) for programs written in Java. The Java swing API is...

4 minutes read.

Sleeping Barber Problem in Java

The barbershop in this issue has one barber, one barber chair, and N chairs for customers in the waiting area. We may demonstrate the issue by keeping with the original...

6 minutes read.

PriorityBlockingQueue Class in Java

What is the Queue? An abstract data structure like Stacks is a queue. A queue is open on both ends. Data is always pushed to one end, called enqueue, and removed...

4 minutes read.

Java String Inbuilt functions

There are different types of inbuilt functions available in the Java String class, all of them are listed below. Char chat At (int index)It outputs the character indicated by the index....

5 minutes read.

Difference between throw and throws in java

This article shows you the core difference between “throw” and “throws”keywords in Java programming language.The throw keyword tells Java you want another part of the code to deal withthe exception,...

2 minutes read.

Minimum XOR value pair in Java

In this section, you will discuss about minimum XOR value pair in Java. The objective is to enforce a value that indicates the least XOR values of the two numbers from...

4 minutes read.