Java Online Compiler
Example: Character Frequency Counter in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Character Frequency Counter import java.util.HashMap; import java.util.Map; // Import Map interface for type hinting // Main class containing the entry point of the program public class Main { public static void main(String[] args) { // Step 1: Define the input string String inputString = "programming language"; // Step 2: Create a HashMap to store character frequencies Map<Character, Integer> charFrequencies = new HashMap<>(); // Step 3: Iterate through each character of the string for (char ch : inputString.toCharArray()) { // Step 4: Check if the character is already in the map if (charFrequencies.containsKey(ch)) { // If yes, increment its count charFrequencies.put(ch, charFrequencies.get(ch) + 1); } else { // If no, add it to the map with a count of 1 charFrequencies.put(ch, 1); } } // Step 5: Print the character frequencies System.out.println("Character frequencies in \"" + inputString + "\":"); for (Map.Entry<Character, Integer> entry : charFrequencies.entrySet()) { System.out.println("'" + entry.getKey() + "': " + entry.getValue()); } } }
Output
Clear
ADVERTISEMENTS