Reputation: 14126
I was asked this question in an interview
If you do something like this,
private int c = d;
private int d;
It results in compile-time error that you
Cannot reference a field before it is defined.
Coming to the interview question,
1 public static int a = initializeStaticValue();
2 public static int b = 20;
3 public static int initializeStaticValue() {
4 return b;
}
5 public static void main(String[] args) {
System.out.println(a);
System.out.println(b);
}
I gave the same response as a
gets initialised by a call to initializeStaticValue() where it is referencing an undefined value b
.
But the programs works fine, gets compile, and prints
0
20
I am confused why
Cannot reference a field before it is defined.
was not thrown.
Secondly, when i debug it, why the control lands at
3 public static int initializeStaticValue() {
I mean, why this is the starting position of the program.
Upvotes: 3
Views: 95
Reputation: 40066
If you are concerned about the order of initialization/execution, here is what is going to happen (I believe it is not very accurate, just giving you an idea):
Foo
, it tries to load Foo
class from classpathFoo
is loaded, with static variables assigned with default value (0 for int)initializeStaticValue()
which returns the value of b
at this moment (0), and assigns it to a
b
with 20.Foo
is successfully loaded & initialized, and JVM calls Foo.main()
Upvotes: 5