Variable initialization and default values

As discussed previous posts , we have seen various types of variables in Java. In this post, i am going to discuss about its initialization and default values.

In Java, when variable is declared as field (static or instance variable inside class), then initialization of that variable is optional. In other words, while declaring field variable you may or may not initialize to its value.

if you are not, then Java runtime assigns default value to it. and when you try to access the variable you get the default value of that variable.

Following table shows variables types and their default values

data type Default value
boolean false
char \u0000
int,short,byte / long 0 / 0L
float /double 0.0f / 0.0d
any reference type null

Here, char primitive default value is \u0000, which means blank/space character.

When you have the variable of reference types then it gets the null as default value.

In following code listing, variables are declared as instance fields. Same is applied for static fields too.

class DefaultValue {
   // here all integers will get value as 0
   byte b;
   short s;
   int i;
   long l;

   // here floating points initialized to value as 0.0
   float f;
   double d;

   // this characters is initialized to blank i.e \u0000
   char c;
   // Boolean is initialized to false
   boolean e;

   // this will get the value as null
   DefaultValue defaultValue;
   String string;
}

But, this is not the case with local variables or block variables.

When you declare any local/block variable, they didn’t get the default values. They must assigned some value before accessing it other wise compiler will throw an error.

Following code snippet shows local/block variables initialization

// this piece of the code can be inside any block
// other code
30:  int a ;
31:  System.out.println(a);
//other code

// above piece of the code, compiler will throw following error
DefaultValue.java:31: variable a might not have been initialized
System.out.println(a);
^
1 error

// so to compile above code , you need to assign value to variable
// other code then use for printing its value
    int a =2;
    System.out.println(a);
// other code

About these ads

6 thoughts on “Variable initialization and default values

  1. dear abhi, as per my understanding boolean default value is platform dependent and in most of the cases its false ,so everyone is considering boolean default value as false……..

  2. Pingback: Getting Started with Google GSON | ajduke's blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s