LearnFrenzy
Sign in Take a free test

Control Flow Statements · Predict the Output · Question 4

Switching on Strings Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

What is the output of the following Java program?

Main.java
public class Main {
    public static void main(String[] args) {
        String[] cmds = {"start", "STOP", "pause", "stop"};
        for (String c : cmds) {
            String r = switch (c) {
                case "start" -> "S";
                case "stop" -> "X";
                case "pause" -> "P";
                default -> "?";
            };
            System.out.print(r);
        }
        System.out.println();
    }
}
  • A S?PX Correct
  • B SXPX
  • C S?P?
  • D SXP?
Correct Answer: Option A

String switches use equals(), which is case-sensitive: "STOP" matches nothing.

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