println()方法在Java中的奇怪行为

class W {
    static int count=0;

    W() {
        count++;
        System.out.print("c ");
    }

    public static void main(String[] args) {
        System.out.println(new W().count+" "+new W().count);
    }
}

预期产量

c 1 c 2

实际输出

c c 1 2

为什么?

解决方法

由JVM执行的事情的实际顺序如下:

>第一W对象被实例化并且其count属性被读取.

这里第一个c发送到输出.
>第二W对象被实例化并且其count属性被读取.

这里第二个c发送到输出.
>构建System.out.println()的字符串参数. (==“1 2”)
>字符串参数发送到输出.

因此,输出结果为c c 1 2.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...