~/ learn/ java-from-zero/ cards/ Capstone: a small Java program, end to end
1 of 5

Type a record with a compact constructor that validates and normalises

Type a record with a compact constructor that validates and normalises

Answer

public record SaleRecord(String productId, double amount, String region) { public SaleRecord { if (amount < 0) throw new IllegalArgumentException("negative amount"); region = region.trim().toUpperCase(); } }

The compact constructor body runs before field assignment. You can validate (throw on bad input) and normalise (reassign region) here. The compiler assigns all components to their fields after the body completes.

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/e17f6566-5fd0-4dc0-a6b0-8b23459362fb/flashcard utf-8 LF