PrintWriter in Java
Fast recall
Quick revision
Core answer
PrintWriter is a character writer with convenient print, println, printf, and format methods. Use it for human-readable or formatted text when its recorded-error model is acceptable and call checkError() when output failure matters.Interview-ready guide
Interview answer
PrintWriter is a Writer designed for convenient text output. It supplies overloaded print and println methods for values, plus printf and format for formatted text. It can wrap another Writer or output stream, and modern constructors allow a charset when it opens a file or byte destination itself.
Its most important behavior is error handling. Methods such as print, println, and write do not propagate IOException; the object records that trouble occurred. checkError() flushes the writer when it is still open and returns whether an error has been recorded. Code that simply prints and never checks can silently miss a disk, pipe, or network failure.
For example, a command-line report can use printf("%-12s %4d%n", name, count) to align columns. A servlet-style text response may also favor the familiar printing API. If the destination is a critical data file where the caller must catch the precise IOException, a BufferedWriter or another ordinary Writer usually gives a clearer failure contract.
The optional auto-flush flag is narrower than its name suggests. Automatic flushing occurs after println, printf, or format; it does not occur after every print or write. Flushing also only pushes buffered data toward the underlying destination—it is not a general durability guarantee for storage.
PrintWriter formats characters; it does not make JSON, CSV, SQL, or HTML safe. Those formats need correct escaping or a dedicated library. It is best used when convenient presentation is the goal, the charset and destination ownership are clear, and the program either checks the error flag or deliberately treats output as best effort.
PrintWriter in Java
Direct Answer
PrintWriter is a character writer with convenient print, println, printf, and format methods. Use it for human-readable or formatted text when its recorded-error model is acceptable and call checkError() when output failure matters.
Deep Dive & Architecture
Most Writer implementations report an output problem immediately by throwing IOException. PrintWriter follows a different design inherited from Java's printing APIs: its output methods catch I/O failures and remember that an error happened. Once set, the trouble state remains observable through checkError(). This makes call sites tidy, but it moves responsibility from exception handling to an explicit status check.
That trade-off suits destinations where printing is naturally best effort or where an outer framework checks the stream. It is riskier in code that must distinguish disk full, broken connection, permission failure, and successful completion. A boolean error flag cannot express the original failure as precisely as a caught IOException.
Auto-flush also needs exact wording. When enabled, println, printf, and format trigger a flush after their output. Plain print, write, and even an embedded newline character do not receive that automatic behavior. Calling close flushes and closes the owned underlying destination according to the wrapper chain.
Finally, formatting and serialization are different jobs. printf applies a format string and locale rules, but it does not quote delimiters or validate structured data. Use a CSV or JSON library for machine-readable records, and reserve PrintWriter for deliberately formatted text or adapters that require its API.
Code Example
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
class PrintWriterErrors {
static final class FailingWriter extends Writer {
public void write(char[] value, int offset, int length) throws IOException {
throw new IOException("destination failed");
}
public void flush() { }
public void close() { }
}
public static void main(String[] args) {
PrintWriter out = new PrintWriter(new FailingWriter());
out.println("report"); // no IOException is thrown here
boolean failed = out.checkError();
if (!failed) throw new AssertionError("failure was not recorded");
System.out.println(failed);
out.close();
}
}
Check your understanding
Answer these without looking back at the article.
- Why does PrintWriter require checkError for reliable output detection?
- Which operations trigger auto-flush?
- When is BufferedWriter a better choice than PrintWriter?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.