0
or 0.0
false
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; }
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);
}
|
>javap -c -classpath . Quark
Compiled from Quark.java
public final class Quark extends java.lang.Object {
public Quark(java.lang.String,double);
}
|