LearnFrenzy
Sign in Take a free test

Records, Enums and Sealed Classes · Predict the Output · Question 1

Looping over enum values Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
enum Signal { RED, AMBER, GREEN }

public class Main {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        for (Signal s : Signal.values()) sb.append(s.name().charAt(0)).append(s.ordinal());
        System.out.println(sb + " " + Signal.valueOf("GREEN").compareTo(Signal.RED));
    }
}
  • A R0A1G2 2 Correct
  • B R1A2G3 2
  • C R0A1G2 -2
  • D RAG 2
Correct Answer: Option A

values() returns constants in declaration order; compareTo subtracts ordinals.

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