Uninitialized Field Read in Constructor
ID |
java.uninit_read_constructor |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
reliability |
Description
Reports fields that are read in a constructor before being assigned a value. Reading an uninitialized field yields the type’s default value (null, 0, false), which is almost always unintended.
Rationale
When a constructor reads a field before assigning it, the field still holds its default value. This is often a bug where the developer intended to use the constructor parameter or assumed the field was already initialized.
public class Config {
private String name;
public Config(String n) {
System.out.println(name); // Bug: reads null
name = n;
}
}
Remediation
Assign the field before reading it, or reorder the constructor statements.
public Config(String n) {
name = n;
System.out.println(name); // Now prints the assigned value
}