#104 Explicit Variable Initilization


One style issue came to my attention while
browsing a Java book in a book store this
weekend. The book (can't remember the title, but
you see it all the time in stores) said that the
following is bad style:

public class Foo {
private int x = 0;
private Bar bar = null;

public Foo() {


The reason is that each instance variable gets
initialized twice, to the same variable. Java
initializes each instance variable to its default
variable (0 or null) before performing any
initialization specified in the code. So in this case,
x gets initialized to 0 twice, and bar gets initialized
to null twice. So there is a minor inefficiency. The
author further goes on to say that this style of
coding is a hold-over from C/C++ style coding,
and that the developer isn't really confident that
Java really initializes instance variables to default
values. He recommends this style:

public class Foo {
private int x;
private Bar bar;

This style seems to be the de-facto standard, as far
as I can tell. When you look at JDK source code,
Fowler examples, J2EE pattern examples, etc., you
usually don't see explicit initialization of instance
variables to default values. Therefore, I'm
requesting a CheckStyle option to support my
team's recent coding standard addition:

"Don't explicitly initialize class or instance
variables to their default values. Only explicitly
initialize an instance variable if you need a non-
default initial value."

Of course, stack variables (declared inside a
method) still have to be explicitly initialized. But
the compiler will let you know if you forget that.


  • Logged In: YES

    Committed to CVS for 3.2 (module ExplicitInitilization)