Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print and println aren't executed in the same time

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 ?

like image 531
yaylitzis Avatar asked Mar 15 '23 17:03

yaylitzis


2 Answers

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.

like image 83
Philip Couling Avatar answered Mar 27 '23 16:03

Philip Couling


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.

like image 36
acesargl Avatar answered Mar 27 '23 16:03

acesargl