Course contentsShow
← Java
Lesson 2018 of 2,87040. File I/O: Character StreamsFree lesson

print and println Methods

Master the basic print and println methods for writing strings and primitives with automatic line breaks.

Writing Text with print and println

You'll learn how to write formatted output to text files using PrintWriter's two most convenient methods.

What They Do

The print and println methods are PrintWriter's workhorses for text output. They accept virtually any Java type—strings, primitives (int, double, boolean, etc.), and even objects—and automatically convert them to text before writing.

The key difference? print writes content without adding anything extra, while println automatically appends a platform-appropriate line break after the output.

Think of print like typing on a single line—everything runs together. The println method is like pressing Enter after each piece of text, moving to the next line automatically.

How They Work

try (PrintWriter writer = new PrintWriter("output.txt")) {
    // print: writes without line break
    writer.print("Hello");
    writer.print(" ");
    writer.print("World");
    
    // println: writes with automatic line break
    writer.println("!");  // Adds newline after !
    writer.println("Next line");
    writer.println(42);           // Converts int to "42"
    writer.println(3.14);         // Converts double to "3.14"
    writer.println(true);         // Converts boolean to "true"
}

Result in output.txt:

Hello World!
Next line
42
3.14
true

Why They're Convenient

No manual string conversion needed—PrintWriter handles everything. No worrying about line terminators (\n vs \r\n)—println uses the correct format for your operating system automatically.

You can chain multiple print calls to build complex lines, then finish with println to complete them.

Key Takeaway: Use print for inline text without line breaks and println for automatic line-terminated output; both accept strings, primitives, and objects with seamless conversion.