Could anyone explain how Java executes this code? I mean the order of executing each statement.
public class Foo
{
boolean flag = sFlag;
static Foo foo = new Foo();
static boolean sFlag = true;
public static void main(String[] args)
{
System.out.println(foo.flag);
}
}
OUTPUT:
false
When class is loaded,
sFlag
andfoo
fields are initialized butfoo
is initialized first!fields
flag
andsFlag
are boolean and can't be null so by default there're false andsFlag
is still false whenfoo
is being initialized.flag = sFlag
after thisflag
is false.That's itfoo
is instantiated during the static initialization of the class, and before sFlag was initialized, and the default value of a boolean is false.Foo is initialized to the instance
2.a The instance member flag is initialized to the value of sFlag (
false
by default)Please refer to JLS §12.4 for more details.
at first static fields should run and at first inline! so at first line 4 and then 5 will run so foo is initialized first and as we know boolean variables are initialized to false by default so at first so as the foo is initialized the field of flag is sflag that's false and then sfalsg becomes true that won't change flag( there's no relation) then at last main runs and print falg that is false!!! I hope to be useful! Be successful
The general order of initialization operations is (after the class is loaded and before first use):
Certainly I don't refer constructors and functions body as a code block above .
I don't know how about
final static
fields. It looks like they follow the rules ofstatic
fields and they cannot be referenced before declaration despite previous comments that they are initialized at compilation step. If they are referenced before there is a compilation error:Maybe
final static
fields can be initialized and compiled into the class file but this is not a general rule and they still cannot be referenced before declaration.Example code to check initialization order:
The above code snipset prints:
foo
is null andsFlag
is falsefoo
) runs:Foo
is createdflag
executes - currentlysFlag
is false, so the value offlag
is falsesFlag
) executes, setting the value to truemain
runs, printing outfoo.flag
, which is falseNote that if
sFlag
were declared to befinal
it would be treated as a compile-time constant, at which point all references to it would basically be inlined totrue
, sofoo.flag
would be true too.