public class d {
    public static void main(String[] args) throws IOException {
      System.out.println(xxxx.test);
    }
}class xxxx{
    public final static String test="abc"; 
    static{
        System.out.println("111");
    } 
}为啥结果为:
abc
那个111怎么不打出来?????

解决方案 »

  1.   

    xxxx.test 已经被等同于"abc"了。
    不用load xxxx类
      

  2.   


    那public final static String test=new String("abc");
    为什么有打呢?
      

  3.   

    你仅仅是引用class类的test变量值
    并没有要求打印
    如果你想打印的话可以用 Class class=new Class();
    这样是把class类放入内存,故会打印
      

  4.   

    不用把,static块里面的语句会在这个类装载的时候执行的。
      

  5.   

    我个人的理解,原代码里程序没有涉及到类的加载,所以不会打印;public final static String test=new String("abc"); 这里有个String,要加载类了,所以打印了。
      

  6.   

    静态常量,分为2种
    1种是编译期常量。比如 static final int,short,等基本类型及 String类型(直接赋值的)
    另外一种是运行期常量 比如 static final long s=System.currentTimeMillis();
    只有真正运行了才能确定下来对于编译期常量,编译的时候就替换掉的,如果引用到,不会直接引起了ide载入
    对于执行期常量,必须等初始化的时候才确定,如果引用到的话,就会引起类的载入和初始化
      

  7.   

    是因为你没有创建类的实例变量啊~大哥~
    你如果在:    public static void main(String[] args) throws IOException {
          System.out.println(xxxx.test);
    中间加一句XXXX A = NEW XXXX();
    比如这样:
    public static void main(String[] args) throws IOException {
    xxxx a = new xxxx();      
    System.out.println(xxxx.test);
    那个111就运行出来了~
      

  8.   

    支持下redduke1202(★及时结贴是一种美德★)
    顺便补充点
    这个问题涉及到类型(类或接口)主动使用和被动使用的问题
    主动使用会导致类型初始化,而被动使用则不会
    以下是6种类型主动使用的情况:创建类的新实例
    调用类的静态方法
    使用类或接口的静态字段,或对其赋值(final static 除外, 原因如redduke1202所说)
    调用API中某些反射方法
    初始化该类的子类
    虚拟机启动时被表明为启动类的类(含有main方法的那个类)
      

  9.   

    class xxxx{
    xxxx(){
    System.out.println(this.getClass().getClassLoader());
    }
        public final static String test="abc"; 
        static{
            System.out.println("111");
        } 
       
    }public class tt extends ClassLoader{
     
    public static void main(String[] args)throws Exception {

    new xxxx();
    tt t=new tt();
    System.out.println(t.findLoadedClass("xxxx"));//为什么总是返回null???
        }
    }
      

  10.   

    public class D {
    public static void main(String[] args) throws IOException {
    System.out.println(xxxx.test);
    }
    }class xxxx {
    public final static String test;
    static {
    System.out.println("111");
    test="abc";
    }
    }
      

  11.   

    同意,没有创建类的实例
    或者
    静态方法在内存中并未被程序的入口main方法调用
      

  12.   

    static 块只有在类被首次实例化的时候才会调用
    这一点和静态常量不同~~