Reputation: 13108
I have the following code:
public class StaticKindOfThing {
static int a =getValue();
static int b = 10;
public static int getValue()
{
return b;
}
public static void main (String []args)
{
System.out.println(a);
}
}
I am aware that default variables are set to 0, however does not it happen at runtime? From the above code it appears that the default initialization to 0 happens before runtime.. otherwise getValue should give a compilation error or runtime exception not finding the value.
So my question is. Does the variable static int b = 10;
get the 0 default value at compilation time?
Upvotes: 2
Views: 208
Reputation: 172378
It gets value which you provide i.e, 10. Static variables are loaded at runtime
When you fire up a JVM and load the class StaticKindOfThing, then static blocks or fields(Here a, b) are 'loaded' into the JVM and become accessible.
From here:-
- It is a variable which belongs to the class and not to object(instance)
- Static variables are initialized only once , at the start of the execution .
- These variables will be initialized first, before the initialization of any instance variables
- A single copy to be shared by all instances of the class
- A static variable can be accessed directly by the class name and doesn’t need any object
EDIT:-
Please go through the Detailed Initialization Procedure
Upvotes: 2
Reputation: 77904
No, it gets value you provided, aka 10.
In your case even you write:
static int a;
the result will be 0
. Because you didn't give any value.
Sometimes you can write static
block like:
static {
//...
}
to be sure that this block runs first before class initiation.
The static initializer block is executed only once when the class is loaded into the JVM like static variable.
Try this one that will do what you think:
public class StaticKindOfThing {
static int a;
static int b = 10;
static{
a = getValue();
}
public static int getValue()
{
return b;
}
public static void main (String []args)
{
System.out.println(a);
}
}
Output: 10
Upvotes: 1