The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
January 2001



This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.


Hello is a bad word in Java

Posted by Kishori Sharan on January 05, 2001 at 10:24 AM

Can't you print a good word like "heaven"? It is not working and it won't work on your machine because you tried to print a word "Hell" java doen't like. Never mind. I am kidding.
Here is the true story. PrintWriter class inherits Writer class. PrintWriter class declares a boolean instance variable autoflush which is set when you are calling its constructor with second arg as true. PrintWriter class also defines a method newLine() which is called from every println method you call. Internally when you call a println method e.g. passing a string like p.println ( "Hello" ); then PrintWriter calls p.print ( "Hello" ) and then it call p.println ( ) which in turn calls p.newLine ( ) where a new line is printed and then it checks if autoflush is true then it flushes the buffer. So all println will work as expected. In your case when you create a PrintWriter then it does likes this in its constructor.
public PrintWriter(OutputStream out, boolean autoFlush) {
this(new BufferedWriter(new OutputStreamWriter(out)), autoFlush);
PrintWriter maintains a private instance varible
private Writer out;
In your case "out" is of type BufferedWriter class.
In case, you call p.print ( "Hello" ) then PrintWriter calls method out.write ( "Hello" ) and write () method is defined in BufferedWriter class which has no knowledge of autoflush attribute you are setting. Certainly it is an overlook on the part of developer of this class. However, BufferedWriter class has a default string size which is 8192. That is ,the write methods looks if the string size in buffer is 8192 then flush it automatically. So if you try to use print () method as

String s = "" ;
for ( int i = 0 ; i <= 8192; i++ ) {
s + = "a" ;
p.print ( s ) ;
then your string s will print and for your knowledge this auto flushing is not happening because you passed "true" in the constructor of PrintWriter it is happening bacuse PrintWriter is using BufferedWriter internally and BufferedWruter flushes all chars if it is 8192 or more. Try using string of size 8191 and it won't work because it is less than 8192.

Your solution is just call p.flush ( ) at the end or call p.close ( ) . Both methods will flush the output on screen.
But, never try to print any Java bad words.....
Certainly I will write this to Sun to make sure whether it is an overlook or they didn't want to do autoflush for print.


  • hello senthil March 17, 2001 at 1:05 PM (0)

Sponsored Links

Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us