Java record default value example code


In Java, record fields are automatically initialized with default values based on their type. Here’s an example that demonstrates the default values assigned to record fields:

public record Person(String name, int age, boolean active) {
    // Record automatically generates constructor, accessors, equals, hashCode, and toString methods
}

public class RecordDefaultValueExample {
    public static void main(String[] args) {
        Person person = new Person(null, 0, false);

        System.out.println("Name: " + person.name());
        System.out.println("Age: " + person.age());
        System.out.println("Active: " + person.active());
    }
}

In this example, we have a Person record class with three fields: name of type String, age of type int, and active of type boolean.

When we create a new instance of the Person record with no values specified (null for String, 0 for int, and false for boolean), the record fields are automatically initialized with their default values.

When we print the values of the record fields, we can observe that the default values are assigned:

Name: null
Age: 0
Active: false

These default values are assigned based on the type of each field. For reference types, the default value is null. For numeric types, the default value is 0 or 0.0 depending on the type. For boolean, the default value is false.

Note that record fields are final and cannot be reassigned once the record object is created. The default values assigned during object creation remain unchanged throughout the object’s lifetime.

It’s important to note that the default values are assigned by the Java runtime and are not configurable or customizable. They follow the standard Java rules for default values based on the field types.

This example demonstrates the automatic assignment of default values to record fields, ensuring that the record object is properly initialized even when no explicit values are provided during object creation.