当前位置: 代码迷 >> J2SE >> 一路java题,为什么答案这样诡异
  详细解决方案

一路java题,为什么答案这样诡异

热度:234   发布时间:2016-04-24 12:31:35.0
一道java题,为什么答案这样诡异
Assembly code
(7)关于以下application的说明,正确的是(        )1.    class   StaticStuff2. { 3.                  static  int  x=10;4.                  static  { x+=5;}5.                  public  static  void  main(String  args[ ])6.                  {7.                       System.out.println(“x=” + x);8.                  }9.                  static  { x/=3;}10.   }A、4行与9行不能通过编译,因为缺少方法名和返回类型    B、9行不能通过编译,因为只能有一个静态初始化器C、编译通过,执行结果为:x=5D、编译通过,执行结果为:x=3

这是那个题
答案是B
我把下面的代码拷贝出来,运行结果是C,求解
Java code
class   StaticStuff {     static  int  x=10;    static  { x+=5;}    public  static  void  main(String  args[])    {            System.out.println("x=" + x);    }    static  { x/=3;}}



------解决方案--------------------
结果等于5是正确的
------解决方案--------------------
class StaticStuff { static int x=10; 
static { x+=5;} // 15
public static void main(String args[]) {
 System.out.println("x=" + x); }
 static { x/=3;} // 5
 } 
按顺序载入static块。
------解决方案--------------------
运行一下这段代码
Java code
class StaticStuff {    static int x = 10;    static {        x += 5;        System.out.println("static x += 5, x = " + x);    }    public static void main(String args[]) {        System.out.println("in main");        System.out.println("x=" + x);    }    static {        x /= 3;        System.out.println("static x /= 3, x = " + x);    }}
------解决方案--------------------
类加载的时候,先加载静态初始化块 再加载静态方法
------解决方案--------------------
探讨

class StaticStuff { static int x=10;
static { x+=5;} // 15
public static void main(String args[]) {
System.out.println("x=" + x); }
static { x/=3;} // 5
}
按顺序载入static块。

------解决方案--------------------
类初始化顺序:初始化父类-初始化子类的静态变量或方法(顺序执行)

你类里面的静态部分都被执行了,所以x是5,最后再进入main方法里被输出的
------解决方案--------------------
答案错误,鉴定完毕,原因见2楼
------解决方案--------------------
只要一加载类就会依次加载静态属性和静态代码块,所以x的值最终是5
------解决方案--------------------
java初级程序员群94321772
------解决方案--------------------
不要迷信答案。。。
------解决方案--------------------
答案B是对的,不懂的去翻书看static块
------解决方案--------------------
  相关解决方案