LearnFrenzy
Sign in Take a free test

Control Flow Statements · Predict the Output · Question 3

A switch expression with grouped labels and yield Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
public class Main {
    public static void main(String[] args) {
        int total = 0;
        for (char c : "a1b2!".toCharArray()) {
            int score = switch (c) {
                case 'a', 'e', 'i', 'o', 'u' -> 5;
                case '1', '2', '3' -> {
                    int digit = c - '0';
                    yield digit * 10;
                }
                case '!' -> 100;
                default -> 1;
            };
            total += score;
        }
        System.out.println(total);
    }
}
  • A 136 Correct
  • B 135
  • C 30
  • D 106
Correct Answer: Option A

a: 5, 1: 10, b: 1, 2: 20, !: 100 → 136. Arrow cases never fall through.

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