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
Quite good introduction.
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……..
Do you mean size of boolean primitives are platform dependent ?
thanks !!
Thanks it helped me 🙂