Umesh Kacha
Umesh Kacha

Reputation: 13666

Strange behavior of Java String

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.

Upvotes: 2

Views: 606

Answers (1)

Jeremy
Jeremy

Reputation: 22415

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;
    }
}

Upvotes: 12

Related Questions