2

I came across this program and its not behaving in expected way.

public class StringTest
{
      public static void main(String[] args)
      {
           String s = "Hello world";
           for(int i = 0 ; i < s.length() ; i++)
           {
                System.out.write(s.charAt(i));
           }
      }
}  

If we think it should print Hello world but it prints nothing. What is going on? Any ideas? Thanks in advance.

1
  • 9
    You forgot to flush(). Commented Mar 4, 2011 at 21:01

1 Answer 1

12

You want: System.out.print(s.charAt(i));

As per the API of write:

Note that the byte is written as given; to write a character that will be translated according to the platform's default character encoding, use the print(char) or println(char) methods.

As noted in a comment to your question, if you really wish to use write() you need to flush().


The reason why write(int) doesn't print anything is because it only flushes the stream on \n and when autoFlush is true.

public void write(int b) {
    try {
        synchronized (this) {
        ensureOpen();
        out.write(b);
        if ((b == '\n') && autoFlush)
            out.flush();
        }
    }
    catch (InterruptedIOException x) {
        Thread.currentThread().interrupt();
    }
    catch (IOException x) {
        trouble = true;
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

You're right, but you do not address the main question here: why do characters printed with print() get flushed eventually, whereas characters printed with write() don't?
@Jeremy: what you have added is correct, but if you look at the code, print(char) just calls write(String) which has the same behavior as write(int). So I still don't get it... And then Jonathon answered: @ChrisJ this should be a comment, but to answer the "why": the System class initializes out like this: new PrintStream(new BufferedOutputStream(fdOut, 128), true). It sets the autoFlush to true.
@Jeremy and @Jonathon: I still don't get it, because print() uses write(), and the auto-flush behavior seems to be coded into write()... So why does print() auto-flush, and not write()?
@ChrisJ You had me digging through code because you're right, it doesn't make sense at first. I found that all the print methods call a particular write method that flushes streams. The other write methods (except for the one called by each print print) don't flush the streams. The one the asker used would not auto-flush.
@Jonation: Thanks for mentioning that. I noticed the subtle different, too, but I was in a hurry and didn't get to edit my answer. @ChrisJ: Your observations are worth commending, and very interesting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.