Consider the following code.
public class Action {
private static int i=1;
public static void main(String[] args)
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
:
4338
. Output 4338\n
i
is incremented to 4339
4339
, but System.out.println()
throws a StackOverflowError
before it prints a newline. Output 4339
StackOverflowError
is caught at level N + 1, statement (3) tries to print 4339
and fails for the same reason again. Output 4339
4339
and succeeds (newline is printed correctly). Output 4339\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.