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
实际输出
抄送 1 2
为什么?
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
实际输出
抄送 1 2
为什么?
JVM执行的事情的实际顺序如下:
第一个W对象被实例化并count读取其属性。
这里首先c是发送到输出。
实例化第二个W对象并count读取其属性。
这里的第二个c是发送到输出。
的字符串参数System.out.println()已构建。( == "1 2")
字符串参数被发送到输出。
因此输出结果为c c 1 2。
在这一行:
System.out.println(new W().count+" "+new W().count);
的实例W在评估语句的其余部分之前被实例化。
操作顺序为:
main 中的 println 方法需要知道它的参数是什么,所以 JVM 先构造对象,然后将它们发送给 println 方法
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);
}
因为new W()将调用构造函数 W() 然后它会打印出“C”,然后计数变为 1 然后你再次调用new W(),所以另一个“C”在这里。最后,调用 system.out.println(1 + " " + 2)。然后 1 2 在输出缓冲区中。
这是因为System.out.println先执行构造函数中的语句,然后才执行调用System.out.println。记得System.out.pritnln调用前完全执行的in构造函数System.out.println
的顺序是
System.out.println()被调用,因此打印“C”System.out.println()被调用,因此打印“C”System.out.println打印新计数。class W {
static int count=0;
W() {
count++;
System.out.print("c ");
}
public static void main(String[] args) {
//modify System.out.println(new W().count+" "+new W().count);
System.out.print(new W().count + " ");
System.out.print(new W().count);
}
}
OUTPUT
c 1 c 2
JVM执行的事情的实际顺序如下:
第一个 W 对象被实例化并读取其计数属性。
这里第一个 c 被发送到输出。
实例化第二个 W 对象并读取其计数属性。
这里第二个 c 被发送到输出。
System.out.println() 的字符串参数已构建。(“1 2”)
字符串参数被发送到输出。
因此输出结果为 cc 1 2。
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);
}
}
这与java中的运算符优先级有关。
new运算符比串联运算符具有更高的优先级,这就是为什么第二个 new 运算符优先于串联运算符而第二个 c 正在打印的原因。在第二次调用 new W() 之后,语句将如下所示。
System.out.println(1 +""+2);
输出将是:- cc 1 2