Modern Java · interview question
Why does the 'compact constructor' in a Java Record matter in practice?
Multiple choiceMediumchapter-12-curatedpremiummodern-javajava-records
record Product(String name, double price) { Product { if (price < 0) throw new IllegalArgumentException("Price cannot be negative"); } }Answer and explanation
Correct answer
A. To validate and process input parameters before setting fields
Why
The compact constructor allows you to perform validation or processing of input parameters before they are assigned to the record fields. It is a convenience for handling such logic without the need for a full constructor definition.
Test yourself on Modern Java
A free test with instant, explained results. No account needed.
More Modern Java questions
- Given a Java text block, how does the compiler handle incidental whitespace?
- How do you write a multiline string in Java using text blocks?
- In which scenario is a static factory method preferred over a constructor?
- In Java 17, how would you refactor a switch statement to a switch expression for better readability and safety in a…
- Why does overriding hashCode in a value object change runtime behavior?
- How does using Java text blocks simplify embedding JSON structures in code?