简体   繁体   中英

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();
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM