public class C02 { private static int x =getvalue();
private static int y=5;
public static int getvalue(){return y;}

public static void main(String[] args) 
{
  System.out.println(x);
}
}x 打印出来0 为什么?? 请讲解一下。

解决方案 »

  1.   

    因为你X从Y里边拿到值的时候..
    Y实际上为0.
    当你拿到值之后Y才有了5.
    所以你打印X就是0咯.
    假设你把Y提到第一行写就会有5.
      

  2.   

    代码写成这样 编译也能通过,真是奇怪, 给X赋值的时候,getvalue() 方法其实应该还没有吧??
      

  3.   

    1.x=getvalue();
    2.跳到getvalue:此时,y = 0;
    3.x = y = 0;
    4.y = 5;
    5.打印。
      

  4.   

    1.x=getvalue(); 
    2.跳到getvalue:此时,y = 0;   //此时的,声明y的语句 private static int y=5; 
                                //还没出来, getvalue()返回的y,从哪里冒出来的? 昏了
    3.x = y = 0; 
    4.y = 5; 
    5.打印。
      

  5.   

    int变量没有初始化,默认初始化为0;
    但建议还是手动为变量初始化。
      

  6.   

    使用getvalue();时,y都还没declare , return y; 这条语句不报错的?? 
      

  7.   

    看看这个.一定就明白了.
    public class C02 {

    //private static int y=5;
        private static int x =getvalue();
       // private static int y=5;
        public static int getvalue()
        {
            int y=5;
         return y;
        }
        
        public static void main(String[] args) 
        {
          System.out.println(x);
        }
    }
      

  8.   

    朋友,这个问题是这样的,x被申明为static型,这说明他将在该类第一次被调用时在该类的静态存储单元中被初始化,而且在整个程序执行过程中只有一份!那么当进入程序的时候在运行所有程序之前,程序一定会先初始化,这时成员变量被赋予“0”初值。int型的就被赋予0。然后在运行中程序发现内存中已经有了x静态变量,所以不会创建新的x。所以总是0,如果不将其定义为static,像下面这样,这个问题就解决了!       private int x =getvalue();
        private static int y=5;
        public static int getvalue(){return y;}
        
        public static void main(String[] args) 
        {
         C02 m=new C02();
          System.out.println(m.x);
        }
      

  9.   


    不好意思,刚才的回答还没有完整。
    你也可以用下面的方法,让程序在执行过程中去修改x。而不应该向刚才那样希望在初始化的时候修改x
    private static int x =getvalue();
     
        private static int y=5;
        public static int getvalue(){return y;}
        
        public static void main(String[] args) 
        {
         x=getvalue();
          System.out.println(x);
        }