Java Online Compiler
Example: CharacterFrequencyArray in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// CharacterFrequencyArray import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { String str = "programming"; // Assuming ASCII characters (0-255). // For only lowercase English letters, a smaller array of size 26 could be used: // int[] charFrequencies = new int[26]; and index would be c - 'a'; int[] charFrequencies = new int[256]; // Step 1: Iterate through each character of the string for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); // Step 2: Use the character's ASCII value as an index to increment its count charFrequencies[c]++; } // Step 3: Print the character frequencies System.out.println("Character frequencies (Array):"); for (int i = 0; i < charFrequencies.length; i++) { if (charFrequencies[i] > 0) { // Cast the index back to char to print the character System.out.println((char) i + ": " + charFrequencies[i]); } } } }
Output
Clear
ADVERTISEMENTS