Strange behavior of println () method in Java
•
Java
class W {
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); } }
Expected production
Actual output
Why?
Solution
The actual sequence of things performed by the JVM is as follows:
>The first w object is instantiated and its count attribute is read
Here, the first C is sent to the output. > The second w object is instantiated and its count attribute is read
Here, the second C is sent to the output. > Build system out. String parameter of println() (= = "1 2") > send string parameters to output
Therefore, the output result is C 1.2
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码