加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 05:46:58 所属栏目: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执行的事情的实
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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读