LearnFrenzy
Sign in Take a free test

Strings and StringBuilder · Predict the Output · Question 20

Switching on lower-cased input Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
public class Main {
    public static void main(String[] args) {
        String[] inputs = {"YES", "No", "maybe", " yes "};
        for (String in : inputs) {
            String r = switch (in.strip().toLowerCase()) {
                case "yes", "y" -> "accept";
                case "no", "n" -> "reject";
                default -> "ask again";
            };
            System.out.print(r + " ");
        }
        System.out.println();
    }
}
  • A accept reject ask again accept Correct
  • B ask again ask again ask again ask again
  • C accept reject ask again ask again
  • D accept accept ask again accept
Correct Answer: Option A

Normalising input with strip() and toLowerCase() before switching makes the match case- and space-insensitive.

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