Question 13
Back to Exercise
What is the output of the following Java program?
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!