Java MCQ: Which of the following is true about the constructors in Java Records?
Answer:
Explanation:
In Java Records, you can define custom constructors to perform tasks such as validating input or computing derived fields. Although records automatically generate a canonical constructor (a constructor with parameters matching the fields in the record), you can also define your own constructors if needed.
Here’s an example of a custom constructor in a record:
public record Person(String name, int age) {
public Person {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
}
}
In this example, the custom constructor is used to validate that the age
field is not negative. If an invalid age is provided, an IllegalArgumentException
is thrown. This custom constructor is known as a compact constructor because it does not explicitly list the parameters; it implicitly uses the parameters defined by the record components.
Records can also have other types of constructors, such as additional constructors that take fewer or more parameters than the canonical constructor. This flexibility allows records to be used in a wide range of scenarios while maintaining their primary purpose as immutable data carriers.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html