Shawn Lin
Shawn Lin

Reputation: 21

Unexpected Java Text Output

When I run this code, it outputs blockA blockB blockA.

I expected the output to be blockB blockA blockA.

Why is the output blockA blockB blockA, not blockB blockA blockA?

public class Test
{
    public static Test t1 = new Test();
    {
        System.out.println("blockA");
    }
    static
    {
        System.out.println("blockB");
    }
    public static void main(String[] args)
    {
        Test t2 = new Test();
    }
}

Upvotes: 1

Views: 83

Answers (1)

nagendra547
nagendra547

Reputation: 6302

Here In class, you have put following statement first.

public static Test t1 = new Test();

So it will be execute class initializer

{
        System.out.println("blockA");
}

So blockA will be printed.

Then static initializer is executed

   static
    {
        System.out.println("blockB");
    }

and blockB is printed

finally code inside main function is executed

 Test t2 = new Test();

and that will trigger class initializer again

{
        System.out.println("blockA");
}

and so blockA is printed again.

A detailed description about execution order about class and static initializer is here jls-12.4.2

Upvotes: 2

Related Questions