Java tutorial

In Java, if you don’t set instance variables yourself, they will be set into their default values. For numeric types it will be 0 (or 0.0 for floating-point types), boolean will be set to false and objects to null reference. Read this article to learn more about this mechanism.

The code below demonstrates the mechanism of default initialization of instance variables:

public class Prototyping {
   public static void main(String[] args) {
      Test t = new Test();
      System.out.println(t.numeric); // prints 0
      System.out.println(t.numericFloatingPoint); // prints 0.0
      System.out.println(t.bool); // prints false
      System.out.println(t.obj); // prints null
   }
}

class Test {
   public int numeric;
   public double numericFloatingPoint;
   public boolean bool;
   public Object obj;
}

As we can see, the instance variables got their default values set because we didn’t set any values ourselves.

Default initialization of instance variables takes place in abstract classes as well:

public class Prototyping {
   public static void main(String[] args) {
      Test t = new Test();
      System.out.println(t.numeric); // prints 0
      System.out.println(t.numericFloatingPoint); // prints 0.0
      System.out.println(t.bool); // prints false
      System.out.println(t.obj); // prints null
   }
}

abstract class ATest {
   public int numeric;
   public double numericFloatingPoint;
   public boolean bool;
   public Object obj;
}

class Test extends ATest {
}

Default initialization works only on non-final instance variables. All the final variables must be initialized by programmer, and a final variable can never be set to null reference.

Remember that default initialization works only on instance variables. Local variables must be always initialized by programmer before first use, otherwise compilation error will arise:

public class Prototyping {
   public static void main(String[] args) {
      int numeric;
      System.out.println(numeric); // compilation error: "variable numeric might not have been initialized"
   }
}

Learn more about Java