Java - Default Initialization of Fields


All fields of a class, static as well as non-static, are initialized to a default value.

The default value of a field depends on its data type.

  • A numeric field ( byte, short, char, int, long, float, and double) is initialized to zero.
  • A boolean field is initialized to false.
  • A reference type field is initialized to null.

The following code demonstrates the default initialization of fields.


public class Main {
  byte b;/*from   www  .ja v a2s  .c o m*/
  short s;
  int i;
  long l;
  float f;
  double d;
  boolean bool;
  String str;

  public static void main(String[] args) {
    // Create an object of Main class
    Main obj = new Main();

    // Print the default values for all instance variables
    System.out.println("byte is initialized to " + obj.l);
    System.out.println("short is initialized to " + obj.s);
    System.out.println("int is initialized to " + obj.i);
    System.out.println("long is initialized to " + obj.l);
    System.out.println("float is initialized to " + obj.f);
    System.out.println("double is initialized to " + obj.d);
    System.out.println("boolean is initialized to " + obj.bool);
    System.out.println("String is initialized to " + obj.str);


Related Topic