Modern Java · interview question
Consider a Java Record defined as 'record Product(String name, double price) {}'. What happens if you attempt to add a non-static field to this record?
Multiple choiceHardchapter-12-curatedpremiummodern-javajava-records
record Product(String name, double price) { int stock; }Answer and explanation
Correct answer
D. The code will not compile
Why
Java Records cannot have additional non-static fields outside their component list. Attempts to do so will result in a compilation error, enforcing their role as immutable data carriers.
Test yourself on Modern Java
A free test with instant, explained results. No account needed.
More Modern Java questions
- Given an enum with a method, how can each constant have a different implementation of that method?
- What keyword is used to define a Java Record?
- Which pattern is effectively implemented when using enums to represent singletons?
- How can you iterate over all constants of an enum in Java?
- When designing a domain model, why should you be cautious about using records for classes with business logic?
- How can the use of enums improve the clarity of domain models in Java?