简体   繁体   中英

Print() vs Write() method of System.out

The Javadoc for PrintStream#print(char) states

Prints a character. The character is translated into one or more bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.

So this means that following code should print 2 'a' however prints one 'a' not two.

System.out.print('a');
System.out.write('a');

Can some one help me understand this behaviour

As per the java docs of PrintStream#write

Writes the specified byte to this stream. If the byte is a newline and automatic flushing is enabled then the flush method will be invoked.

So just call flush .

Call System.out.flush(); after System.out.write('a'); .

Alternately ,

As the docs suggest, set the output stream to autoflushable and then write a new line char at the end of your program. In fact the PrintStream object System.out is already set to autoflushable if you look at the source code System class . So really, all you need to do is just print a new line character in the end. No need to call flush.

System.out.print('a');
System.out.write('a');
System.out.write('\n');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM