Must Know Rules of Static Blocks, Methods and Variables

Must Know Rules of Static Blocks, Methods and Variables

First the meaning of static, Whether it is used with a variable or a method static keyword is of the whole class. It does not belong to objects of the class.

Now rules,

  1. Firstly, static blocks are executed then the public static void main(String... args) method is run when static blocks and PSVM method are present under the same class.

    Untitled.png

  2. If static blocks and PSVM are present in a different class then PSVM is executed first,

    Untitled2.png but if the object of another class containing the static blocks is created then static blocks are called first. Untitled3.png

  3. Static Blocks are executed when the object is created, but static variables and methods won't execute unless they are explicitly called out by an object or directly by a class.

    Not Called Explicitly Untitled4.png Called Explicitly Untitled5.png

  4. Static Blocks get executed in order.

  5. Static Variables are created in the method area of JVM.
  6. Only Inner Class can be static, the Outer class cannot be.
  7. Static Members and Methods can be called through objects also.
  8. This and Super Keyword can't be used with static because these keywords refer to the object but in static context object itself is called later.

Thank you! for reading :)