Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

io.StringWriter: practical reference

io.StringWriter: practical reference: StringWriter collects characters in a StringBuffer; close has no effect and getBuffer exposes mutable backing storage.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

java.io.StringWriter

StringWriter collects characters in a StringBuffer; close has no effect and getBuffer exposes mutable backing storage.

Use StringWriter when an API requires Writer but the complete result should become an in-memory String; getBuffer exposes the same buffer.

close and flush do not prevent further writes, so it does not model resource ownership. Unbounded output can exhaust memory.

A new writer yields the empty String. Mutating the StringBuffer returned by getBuffer immediately changes the result.

The example exercises the documented element in a small deterministic program and compares exact standard output.

Examples

public class Main {
    public static void main(String[] args) throws Exception {
        var writer = new java.io.StringWriter();
        writer.write("Java");
        System.out.println(writer.toString());
    }
}

Result

Java

The example exercises the documented element in a small deterministic program and compares exact standard output.

Sources