Character Frequency in Java Strings

JavaJavaBeginner
Practice Now

Introduction

In Java, String class provides several methods that can be used to find character frequency. The replace() method, chars() method, and custom loop can be used to find the character occurrence in a string. In this lab, we will use these methods to count occurrence of a character in a Java String.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("`Classes/Objects`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/DataStructuresGroup -.-> java/arrays("`Arrays`") java/BasicSyntaxGroup -.-> java/comments("`Comments`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/for_loop("`For Loop`") java/BasicSyntaxGroup -.-> java/if_else("`If...Else`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/BasicSyntaxGroup -.-> java/variables("`Variables`") java/SystemandDataProcessingGroup -.-> java/string_methods("`String Methods`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/scope -.-> lab-117431{{"`Character Frequency in Java Strings`"}} java/classes_objects -.-> lab-117431{{"`Character Frequency in Java Strings`"}} java/class_methods -.-> lab-117431{{"`Character Frequency in Java Strings`"}} java/modifiers -.-> lab-117431{{"`Character Frequency in Java Strings`"}} java/oop -.-> lab-117431{{"`Character Frequency in Java Strings`"}} java/identifier -.-> lab-117431{{"`Character Frequency in Java Strings`"}} java/arrays -.-> lab-117431{{"`Character Frequency in Java Strings`"}} java/comments -.-> lab-117431{{"`Character Frequency in Java Strings`"}} java/data_types -.-> lab-117431{{"`Character Frequency in Java Strings`"}} java/for_loop -.-> lab-117431{{"`Character Frequency in Java Strings`"}} java/if_else -.-> lab-117431{{"`Character Frequency in Java Strings`"}} java/operators -.-> lab-117431{{"`Character Frequency in Java Strings`"}} java/output -.-> lab-117431{{"`Character Frequency in Java Strings`"}} java/strings -.-> lab-117431{{"`Character Frequency in Java Strings`"}} java/variables -.-> lab-117431{{"`Character Frequency in Java Strings`"}} java/string_methods -.-> lab-117431{{"`Character Frequency in Java Strings`"}} java/system_methods -.-> lab-117431{{"`Character Frequency in Java Strings`"}} end

Create a Java file

Create a new Java file named CharOccurrence.java in the ~/project directory and open it in a text editor.

cd ~/project
touch CharOccurrence.java

Using replace() method

In this step, we are using the replace() method to find the count of a character in the string.

public class CharOccurrence {
	public static void main(String[] args){
		String str = "abracadabra-banana";
		System.out.println(str);
		// count occurrence
		int count = str.length() - str.replace("a", "").length();
		System.out.println("occurrence of a: "+count);
	}
}

Save and close the file. Compile the Java program with the following command:

javac CharOccurrence.java

Execute the Java program with the following command:

java CharOccurrence

Using chars() and filter() methods in Java 8

In this step, we are using the chars() method that returns a stream of characters and then using filter() method to get all the specified character present in the string. The count() method is used to get count of the filtered stream.

public class CharOccurrence {
	public static void main(String[] args){
		String str = "abracadabra-banana";
		System.out.println(str);
		// count occurrence
		long count = str.chars().filter(ch -> ch == 'a').count();
		System.out.println("occurrence of a: "+count);
	}
}

Save and close the file. Compile the Java program with the following command:

javac CharOccurrence.java

Execute the Java program with the following command:

java CharOccurrence

Using a custom loop

This is a conventional solution of finding a character count in the string. Here, we are using a loop to traverse each character of the string and comparing character by using the charAt() method that returns a character present at the specified index and finally counting if a character matches the desired character.

public class CharOccurrence {
	public static void main(String[] args){
		String str = "abracadabra-banana";
		System.out.println(str);
		// count occurrence
		int count = 0;
	    for (int i=0; i < str.length(); i++)
	    {
	        if (str.charAt(i) == 'a')
	        {
	             count++;
	        }
	    }
		System.out.println("occurrence of a: "+count);
	}
}

Save and close the file. Compile the Java program with the following command:

javac CharOccurrence.java

Execute the Java program with the following command:

java CharOccurrence

Summary

In this lab, we learned three different methods to count the occurrence of a character in a Java string. We used the replace(), chars() and filter() methods, and custom loop. All the methods are quite easy to use. You can use any of the above per your convenient and use case.

Other Java Tutorials you may like