One of the most fundamental aspects of a programming language is how it initializes data. For Java, this is defined explicitly in the language specification. For fields and array components, when items are created, they are automatically set to the following default values by the system:
- numbers: 0 or 0.0
- booleans: false
- object references: null
This means that explicitly setting fields to 0, false, or null (as the case may be) is unnecessary and redundant. Since this language feature was included in order to, in part, reduce repetitive coding, it's a good idea to take full advantage of it. Insisting that fields should be explicitly initialized to 0, false, or null is an idiom which is likely inappropriate to the Java programming language.
Furthermore, setting a field explicitly to 0, false, or null may even cause the same operation to be performed twice (depending on your compiler).
Example
public final class Quark { public Quark(String aName, double aMass){ fName = aName; fMass = aMass; } //PRIVATE //WITHOUT redundant initialization to default values //private String fName; //private double fMass; //WITH redundant initialization to default values private String fName = null; private double fMass = 0.0d; }
If the bytecode of the Quark class is examined, the duplicated operations become clear (here, Oracle's javac compiler was used):
WITHOUT redundant init | WITH redundant init |
---|---|
>javap -c -classpath . Quark
Compiled from Quark.java public final class Quark extends java.lang.Object { public Quark(java.lang.String,double); } Method Quark(java.lang.String,double)
|
>javap -c -classpath . Quark
Compiled from Quark.java public final class Quark extends java.lang.Object { public Quark(java.lang.String,double); } Method Quark(java.lang.String,double)
|