×

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

Spliterator in Java 8

In this tutorial, we will understand the meaning of spliterator in java 8. It is just like any other iterator available in java used to traverse the elements of either...

4 minutes read.

How to install Java in Windows 10

To make programs that can run on our systems, we need to install the programming language related software in our systems. Different programming language requires a different type of software aka...

6 minutes read.

Graphics Program in Java

Graphics Program in Java The graphics program in Java is part of the Swing program in Java. In this section, we will learn about the implementation of custom graphics using some...

6 minutes read.

Sierpinski Number in Java

The Sierpinski triangle—is it a fractal? The Sierpinski Triangle fractals. A self-similar fractal is the Sierpinski triangle. It is made of an equilateral triangle with its residual area successively reduced by...

3 minutes read.

Java String length() method

Java String length() method returns length of the characters in a String. Syntax: public int length() Returns It returns length of the characters Java String length() method example 1          public class JavaStringLengthEx1  ...

1 minute read.

Minimum Number of Taps to Open to Water a Garden in Java

Problem Statement The issue is that a gardener wants to water a (single-dimensional) garden using the fewest possible tap openings. The goal is to determine the minimum necessary taps to be...

8 minutes read.

Sorting Algorithms in Java

Sorting Algorithms in Java Sorting is the technique that puts the elements of an array or list either in descending or ascending order. For example, take an array A, whose elements...

3 minutes read.

JIT in Java

What is JIT ? JIT stands for " Just in Time Compiler ". It is called "Just in time" because it is called at the very last moment when the interpretation...

5 minutes read.

Annotations in Java

Annotations in Java Java Annotations are metadata about the source code. They do not have any direct effect on the execution of the java program. Annotations in Java were introduced in...

4 minutes read.

Java LinkedList vs ArrayList

LinkedList In LinkedList, each element is a distinct entity containing an information portion and an address component, and the elements are not kept in consecutive locations. Pointers & addresses are used...

3 minutes read.

New Features of Java 14

 Features like Switch expressions and text blocks which are previewed in Java 13 version are standardized in Java 14. Features in Java 14 Switch ExpressionText BlocksRecordsNull Pointer ExceptionsInstance ofPackaging ToolGarbage collectors 1.Switch Expressions Switch...

3 minutes read.

Polygonal Number in Java

What does a Java Polygonal Number Mean? In mathematics, a polygonal number refers to a number that is expressed through dots or pebbles arranged in a regular polygonal pattern. Alphas are...

4 minutes read.

Association in Java

In Java, association refers to the link between two classes established by their objects. One-to-one, one-to-many, and many-to-many connections are managed via association. The Association defines the multiplicity between objects...

5 minutes read.

&amp;&amp; Operator in Java

“ && ” is the conditional - And operator in Java. In Java, it is an example of a logical operator. In Java, the “ & ” operator has two...

3 minutes read.

Java Thread Priority in Multithreading

As we realise, java, being object-situated, works inside a multithreading climate in which the string scheduler relegates the processor to a string in light of the need for a string....

6 minutes read.

How Many Ways to Create Objects in Java

Introduction Java comes under the category of object-oriented programming languages. Since it is object-oriented, everything in Java is considered an object. Java is a diverse programming language that is designed to...

6 minutes read.

Add Time in Java

Before Java 8, java.util.Date was one of the most usually involved classes for addressing date-time values in java. Then Java 8 presented java.time.LocalDateTime and java.time.ZonedDateTime. Java 8 likewise permits us...

6 minutes read.

ArrayList vs Vector in Java

ArrayList Vs. Vector in Java In Java, the two classes ArrayList and Vector both are associated with Java Collections Framework. Both classes implement java.util.List interface. Even so, these classes have noticeable...

4 minutes read.

Binary Strings Without Consecutive Ones in Java

N, an integer, is provided. Our objective is to determine the overall number of strings with length N that do not include successive 1s. Example: Input: 3 Output: 6 Explanation The binary forms of length...

6 minutes read.

Java Integer decode() method

The decode() method of Integer class decodes a String into an Integer. It can accept decimal, hexadecimal and octal numbers. Syntax public static Integer decode(String nm) throws NumberFormatException Parameters The parameter ‘nm’ represents the...

2 minutes read.