Print and println aren't executed in the same time

108 views Asked by At

I have a method in my servlet where I have some prints to the console..

   private void collectingWorkPositions(HttpSession session, HttpServletRequest request)
   {       
     System.out.println("Collecting1..");

     //code...                

     System.out.println("Collecting2..");

     //code...

     System.out.print("printing p: ");
     for(Integer i:p)
         System.out.print(i + " ");
   }

When this method iscalled, only

Collecting1..
Collecting2..

are printed in the console. When I am refreshing the JSP page, only then the last print (without the ln) isprinted. I know that the difference between these two is that println will print on a new line where print will print at the same line, so why is this not happening here in the same action ?

2

There are 2 answers

0
Philip Couling On BEST ANSWER

This is related to the fact you never terminate the line. This is either something to do with java not flushing, or to do with the log handler waiting until the end of line before writing to the log.

Add a final System.out.println() or System.out.print('\n') at the end to fix it.

0
acesargl On

System.out (as cout in c++ and stdout in C) is buffered (a buffered stream). The system flushes the content of the buffer when the buffer is full or when it finds a "newline" character.

println includes a newline charecter, but print does not. If you want to force the content to be sent then include:

System.out.flush();

after the for statement.