Question 1
IntermediateControlling Program Flow · Create program flow control constructs including if/else, switch statements and expressions, loops, and break and continue statements.
A financial application uses a sealed interface Transaction to represent various payment methods. The interface permits three record classes: CreditCard, BankTransfer, and DigitalWallet. You are writing a method to process these transactions using a switch expression with pattern matching.
public sealed interface Transaction permits CreditCard, BankTransfer, DigitalWallet {}
public record CreditCard(String pan, double amount) implements Transaction {}
public record BankTransfer(String iban, double amount) implements Transaction {}
public record DigitalWallet(String id, double amount) implements Transaction {}
// In a service class:
public String process(Transaction t) {
return switch(t) {
case CreditCard c when c.amount() > 1000 -> "High Value CC";
case CreditCard c -> "Standard CC";
case BankTransfer b -> "Bank Transfer";
// Missing case
};
}
Which statement is true regarding the compilation of this code?
Answer and explanation
Correct answer: D
A switch expression over a sealed interface must cover every permitted subtype or have a default. No case handles DigitalWallet, so the compiler rejects the switch. The when guard is a standard Java 21 feature.
