Java Record Static Field Compilation Fix
Given the code fragment: Which action enables the code to compile? - 
Community Votes
100% of anonymous learners picked answer E. Votes are pick records left by other test-takers — they are not the verified answer.
Community Insight
The exam traps candidates who do not know that record components are implicitly final instance fields, meaning any additional field must be static.
This question tests the rule that Java records cannot have non-static instance fields. Replacing the initialization with a static variable is the correct way to compile this code.
Candidates often choose option C, thinking the error is due to duplicate initialization, failing to realize the fundamental issue is the instance nature of the field.
Community Discussion (5 comments)
Comments & Corrections
No comments yet — spotted an error or have a note? Share it below.
Expert Analysis
Why the Answer Is Correct
The Java Language Specification (JLS) explicitly states that a record declaration may contain only static members in its body. The code fragment attempts to declareregNo as an instance variable (int regNo = 100;). Since records automatically generate final instance fields for their components, adding another non-static instance field results in a compile-time error. Making regNo static (Option E) satisfies the JLS requirement.Why the Other Options Are Wrong
Option A is invalid becausevoid is not a type that can be used as a class or record modifier in this context. Option B (class) would work if the field remained non-static, but the question asks what action enables the record code to compile, and changing it to a class changes the type entirely. Option C fails because even if you remove the explicit initialization, the compiler still rejects non-static fields in records. Option D is incorrect because access modifiers do not change the instance/static nature of the field.Community Comment Notes
The community consensus is unanimous, with all votes pointing to E. As ASPushkin noted, referencing "jls17 8.10", the spec forbids non-static fields. Users like Uteman confirmed that "Records only allow static variables". This confirms the strict nature of record definitions in modern Java.Official Reference
Exam Strategy
Always check if a data structure is a Record. If it is, remember that only static fields are allowed in the body. Do not confuse record components (which are instance fields) with additional fields defined in the body.
Frequently Asked Questions
Why can't I add a non-static field to a Java record?
Records are designed to be immutable data carriers. Non-static fields would break the implicit immutability and canonical constructor contract.
Can I use a class instead of a record here?
Yes, a standard class allows non-static instance fields, but the question specifically asks how to fix the record code.