各位高手请帮我看看这道题(一个java新手)

public  class Test2 {



    static int x = 10;

    static

    {

        x += 5;

    }

   



    static

    {

        x /= 3;

        System.out.println("x = " + x);

    }



    public static void main(String[] args)

    {

        System.out.println("x = " + x);

    }

}



为什么输出为

x = 5

x = 5





而改成

public  class Test2 {



    static int x = 10;

    static

    {

        x /= 3;

        System.out.println("x = " + x);

    }

    static

    {

        x += 5;

    }

    public static void main(String[] args)

    {

        System.out.println("x = " + x);

    }

}

输出为

x = 3

x = 8





    static

    {

        x += 5;

    }

输出为

x = 3

x = 3





对于static 和块,还有 /= 不是和理解,现在去搜索,在这里发表希望能有人帮我更全面的解答,谢谢!





你只需要明白这一点就可以了,static是在类加载的时候就执行了,并且按照从上到下的顺序执行的,这样就能理解了

static的东西是jvm在加载.class文件的时候就被执行掉的 执行的顺序是你定义的顺序 然后在执行非static的变量或块的初始化
x/=5 ==> x=x/5