Static variables: Are the class variables and they are not created separately for each object of the class.
Instance variables: Are also the class variables but are created for each object separately.
The above definitions are just for references.
Please explain why i am getting error in this class declaration.I know it is just because i have not of initialised x.
class non_static{
public static void main(String args[])
{
int x;
System.out.println(x);
}
}
But this class declaration is totally fine.
class static_example{
static int x;
public static void main(String args[])
{
System.out.println(x);
}
}
And output of this program is 0.
Please do explain me why static member is initialized with the default value while local variables are not.
If you want to know the background on why Java specifies it like that, it has to do wih the limits of static code analysis. Memory allocated from the stack (and this is where the local vars are) can be confirmed positively by the compiler to be initialized before use. Not so with heap-allocated storage (static vars, instance vars). This is why the JLS requires the implementations to always zero out any heap storage before exposing a pointer to it.