Assignment of default values to fields in general case is redundant, because the value will be there according to JLS. However in case of volatile field there is also performance issue, consider benchmark
@State(Scope.Thread)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(value = Mode.AverageTime)
@Fork(jvmArgsAppend = {"-Xms4g", "-Xmx4g"})
public class VolatileFieldBenchmark {
@Benchmark
public Object explicitInit() {
return new Class1();
}
@Benchmark
public Object noInit() {
return new Class2();
}
private static class Class1 {
private volatile boolean field = false;
public boolean isField() {
return field;
}
public void setField(boolean field) {
this.field = field;
}
}
private static class Class2 {
private volatile boolean field;
public boolean isField() {
return field;
}
public void setField(boolean field) {
this.field = field;
}
}
}
The benchmark demonstrates that instantiation of a class without default value assignment takes less time:
Benchmark Mode Cnt Score Error Units
VolatileFieldBenchmark.explicitInit avgt 40 11.087 ± 0.140 ns/op
VolatileFieldBenchmark.noInit avgt 40 3.367 ± 0.131 ns/op
Comment From: jhoeller
Well spotted, a good general rule to follow! Thanks for raising this.