class abc {
int a = 0;
static int b;
static abc h = new abc(); //line 4
public abc() {
System.out.println("cons");
}
{
System.out.println("ini");
}
static {
System.out.println("stat");
}
}
public class ques {
public static void main(String[] args) {
System.out.println(new abc().a);
}
}
When i wrote this code I am getting output in order like this:
ini
cons
stat
ini
cons
0
Here when I created a new object in main(), class abc
got loaded and static
variables and blocks are executed in order they are written. When control came to line 4 static abc h = new abc();
Instance Initialization block is called. Why? why is static block not called when a new object is created at line 4 and till that time static block was also not called even once, so according to convention static block should have been called. Why is this unexpected output coming?
Static Method Static methods are the methods in Java that can be called without creating an object of class. They are referenced by the class name itself or reference to the Object of that class.
Since static variables belong to a class, we can access them directly using the class name. So, we don't need any object reference. We can only declare static variables at the class level. We can access static fields without object initialization.
The static keyword is a non-access modifier used for methods and attributes. Static methods/attributes can be accessed without creating an object of a class.
The static variable can be used to refer to the common property of all objects (which is not unique for each object), for example, the company name of employees, college name of students, etc. The static variable gets memory only once in the class area at the time of class loading.
JLS says:
The static initializers and class variable initializers are executed in textual order, and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope (§8.3.2.3). This restriction is designed to detect, at compile time, most circular or otherwise malformed initializations.
Which is exactly your case.
Here is your original example: http://ideone.com/pIevbX - static initializer of abc
goes after static instance of abc
is assigned - so static initializer can't be executed - it's textually after static variable initialization
Let's move line 4 after static initialization block - http://ideone.com/Em7nC1 :
class abc{
int a = 0;
static int b;
public abc() {
System.out.println("cons");
}
{
System.out.println("ini");
}
static {
System.out.println("stat");
}
static abc h = new abc();//former line 4
}
Now you can see the following output:
stat
ini
cons
ini
cons
0
Now initialization order is more like you expected - first called static initializer and then static instance of abc
is initialized in common manner.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With