LearnFrenzy
Sign in Take a free test

Arrays in Java · Predict the Output · Question 13

Counting letters with an int array Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 13 Back to Exercise

What is the output of the following Java program?

Main.java
public class Main {
    public static void main(String[] args) {
        int[] count = new int[26];
        for (char ch : "mississippi".toCharArray()) count[ch - 'a']++;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 26; i++) if (count[i] > 0) sb.append((char) ('a' + i)).append(count[i]);
        System.out.println(sb);
    }
}
  • A i4m1p2s4 Correct
  • B m1i4s4p2
  • C i4s4p2m1
  • D m1i1s1p1
Correct Answer: Option A

ch - 'a' maps letters to indexes 0–25; walking the array prints letters in alphabetical order.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links