LearnFrenzy
Sign in Take a free test

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

Record patterns with guards in a switch Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
sealed interface Txn permits Credit, Debit { }
record Credit(String acc, int amount) implements Txn { }
record Debit(String acc, int amount) implements Txn { }

public class Main {
    static String classify(Txn t) {
        return switch (t) {
            case Credit(String acc, int amt) when amt >= 10000 -> "large credit to " + acc;
            case Credit(var acc, var amt) -> "credit " + amt;
            case Debit(var acc, var amt) when amt > 5000 -> "flag debit " + amt;
            case Debit d -> "debit " + d.amount();
        };
    }

    public static void main(String[] args) {
        Txn[] ts = {new Credit("A1", 15000), new Debit("A1", 7000), new Credit("B2", 500), new Debit("B2", 300)};
        for (Txn t : ts) System.out.println(classify(t));
    }
}
  • A large credit to A1 flag debit 7000 credit 500 debit 300 Correct
  • B credit 15000 debit 7000 credit 500 debit 300
  • C large credit to A1 debit 7000 credit 500 debit 300
  • D Compilation error
Correct Answer: Option A

Cases are tried in order; guarded record patterns come before the unguarded ones for the same type.

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