简体   繁体   中英

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.

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

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