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 
                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.
Note: To create a static member(block, variable, method, nested class), precede its declaration with the keyword static. When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object.
You can construct a new object from within a static method and then you can call that object's methods, even if they are not static and even if that object is an instance of the same class. Static methods belong to the class. There is just one of them and they don't need to be constructed.
foo is null and sFlag is falsefoo) runs: Foo is createdflag executes - currently sFlag is false, so the value of flag is falsesFlag) executes, setting the value to truemain runs, printing out foo.flag, which is falseNote that if sFlag were declared to be final it would be treated as a compile-time constant, at which point all references to it would basically be inlined to true, so foo.flag would be true too.
foo 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.
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