Task 1 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

(Optional) 6.4 Writing files — PrintWriter basics

Lesson

Optional lesson — beyond the AP CS A exam. Writing to files is not on the AP exam (which only reads files); this is here for a fuller picture of Java.

Writing text output

A PrintWriter writes text, just like System.out. It has print (no line break) and println (adds a line break). After writing, call flush() to make sure everything is sent, or close() when finished.


Worked example

PrintWriter out = new PrintWriter(System.out);
out.println("Line 1");
out.print("No newline ");
out.println("here");
out.flush();

println ends the line; print does not. flush() pushes the text out. Here it writes to the screen; the next lesson writes to a file with the very same methods.


▶ Try it: run this, then add more print/println calls and re-run.



Which PrintWriter method adds a line break?


Why call flush() after writing?


Type exactly what this program prints.

PrintWriter out = new PrintWriter(System.out);
out.print("Hi ");
out.println("there");
out.println("bye");
out.flush();

Match each method to what it does.


True or false?