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
。
关于java - Java 中 println() 方法的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18976868/