why does '\n' act as flush() method? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

why does '\n' act as flush() method?

I was using the System.out.write() method from java. I noticed that when i use the method by itself nothing gets outputted. Yet when I use System.out.flush() method right after, I see output. The same thing also happens when i use System.out.write('\n') after. My question is why does writing a newline have the same functionality as flushing the buffer? Here is the source code: https://code.sololearn.com/cS4rw44J1Mv2/#java

5th Dec 2020, 8:46 PM
pNK
pNK - avatar
2 Answers
+ 2
Interesting I didnt know this.. this works also System.out.write('A'); System.out.print("."); //prints "A." I'll have a look around to see if I can figure it out
5th Dec 2020, 9:01 PM
D_Stark
D_Stark - avatar
+ 1
Martin Taylor System.out is of the type PrintStream so it can access all the methods in the PrintStream class and in the PrintStream class there is a method called write which "writes the specified byte to this steam". Yes, I know that System.out.print() is the more convenient option but I was reading the book "Java A Beginning Guide" and came across this. I've seen it on a youtube video that if you don't use the flush method after the write method, nothing gets written but in the book I see that they use System.out.write('\n') to still do the same thing that flush does. My question is why is it that when you write a new line it basically had the same functionality as flushing the buffer and is there a difference
5th Dec 2020, 10:07 PM
pNK
pNK - avatar