Day29 : Static Block

 Static Block

1) A Static Block in Java in a block which is created outside any method but inside class Body using the keyword static.
2) The general sentence of writing static block is 
    class<class Name>
    {
        static
        {
            ..........
            ..........
        }
    Other member of the class
    }

3) Java executes static block only one and automatically.
4) This happens when we make 1st use of the class.

What is the first use of the class

In Java the first use of the class when either of the following 2 situation occur:
1) We make the first object of the class Or
2) We access any static member of that class for the 1st time Whichever of the above 2 happens 1st, it is called 1st use of the class.

What java does when we make 1st use of the class?

Whenever we make 1st use of the class Java does 3 thing:
1) It loads the class in memory
2) If the class contains any static member then it allocate space for that static member in method area.

class Emp
{
    public static string compname = "Google";
    public Emp()
    {
        System.out.println("Emp constructor called");
    }
    static
    {
        System.out.println("Static Block1 called");
    }
    static
    {
        System.out.println("Static Block2 called");
    }
    static
    {
        System.out.println("Static Block3 called");
    }

class UseEmp
{
    public static void main(String [ ] args)
    {
        ........
    }
}

Output : 
        Static Block1 called
        Static Block2 called
        Static Block3 called
        Google
        Google

Special Rule on restricting static block and static method

Java puts an important restriction on static block and static method. The restriction is that a static block and a static method can only access static data and not instance variable(non static data member) of the class. Otherwise java will generate syntax-error.

class
{
    private int a = 10;
    public static void main(String [ ] args)
    {
        //Wrong Code will not even complile
        System.out.println(a)
        //perfect code, will compile and run
        Test t = new Test();
        System.out.println(t.a)
     }
 }



    

Comments

Popular posts from this blog

Day2 : Compiling Java Program with Examples

Day1: Introduction to Java and its feature

What does System.out.printf( "%-15s%03d\n", s1, x) do?