Note the absence of newline characters in 433943394339
. It indicates that something wrong happens inside System.out.println()
.
The essential point here is that System.out.println()
requires some stack space to work, so that StackOverflowError
is thrown from System.out.println()
.
Here is your code with marked points:
public static void main(String[] args) {
try{
System.out.println(i); // (1)
i++;
main(args); // (2)
}catch (StackOverflowError e){
System.out.println(i); // (3)
i++;
main(args); // (4)
}
}
Let’s imagine what happens at level N of recursion when i = 4338
:
- Statement (1) at level N prints
4338
. Output4338\n
i
is incremented to4339
- Control flow enters level N + 1 at (2)
- Statement (1) at level N + 1 tries to print
4339
, butSystem.out.println()
throws aStackOverflowError
before it prints a newline. Output4339
StackOverflowError
is caught at level N + 1, statement (3) tries to print4339
and fails for the same reason again. Output4339
- Exception is caught at level N. At this point there is more stack space available, therefore statement (3) tries to print
4339
and succeeds (newline is printed correctly). Output4339\n
i
is incremented and control flow enters level N + 1 again at (4)
After this point the situation repeats with 4340
.
I’m not sure why some numbers are printed correclty between sequences without newlines, perhaps its related to internal work of System.out.println()
and buffers it uses.