Search code examples
javastack-overflowprintln

Why multiple calls of System.out.println prints values in single line


It is just a funny question. Not a real code for production. I do not want to fix it. I just want to understand this strange behavior. I have the code that should print "1" in each line. Actually, it is false. I get the strange result like "11111111" in one line.

class Scratch
{
  public static void main( String[] args )
  {
    method();
  }

  static void method()
  {
    try
    {
      System.out.println(1);
      method();
    }
    catch ( StackOverflowError e )
    {
      method();
    }
  }
}

Output could be the following:

1
11111
1
11111
1
1
1
1
1
11111111
1
11111

Solution

  • While, as @khelwood said in a comment, you shouldn’t have any specific expectations to a program that ignores repeated StackOverflowErrors. About anything may go wrong.

    However, an attempt at a not too unlikely explanation: System.out.println(1) consists of printing 1 and the platform-specific new-line sequence — on Windows again consisting of printing \r and \n. There is nothing stopping the stack overflow from happening between the two or when trying to print the newline after the 1 has been successfully printed. In these cases the next 1 (if successful) will be printed on the same line.

    Your output seems to show about 30 1 and about 12 (full) newlines. So apparently the scenario I sketched has happened a little more than half of the times. If this is the correct explanation, which we don’t know.