Reputation: 425
The following code compiles successfully. As per my understanding variables have to be declared before using them then what exactly is happening here
class A {
static {
y=20;
z=10;
}
static int z;
static int y=30;
{
w=10;
}
int w;
public static void main(String args[]){
System.out.println(y);
}
}
Modified the question after reading the comments. Here the output is 30. So variable declaration happens first, then all the initialization statements are executed as per order of appearance
Upvotes: 0
Views: 67
Reputation: 274443
variables have to be declared before using them
This is only partially right. If you are in a method and you do this:
System.out.println(i);
int i = 0;
Obviously it won't compile.
But when you are declaring a variable at class level, this rule does no hold. In your code, just because w
's declaration is written a few lines after it is being used (w = 10;
), it does not mean that the line int w;
is executed after the line w = 10;
.
Think of it like this: the compiler will see all the static fields' declarations (class level variables) first, then all the non-static fields', then the code blocks (constructors, methods etc) in the class. In your code:
class A {
static {
z=10;
}
static int z;
{
w=10;
}
int w;
}
the compiler sees z
first, then w
. Then let's suppose you access A
for the first time in some other parts of your code. Now the static block is executed (z=10;
). Let's suppose again that you are actually creating a new instance of A
, now w=10;
will get executed.
Upvotes: 1
Reputation: 6574
Variables are declared by the classloader when it loads the class.
Static block will be evaluated first time the class is accessed so in that time the member variables will be declared, so the order does not really matter
Upvotes: 1