Java Output Methods: Complete Guide to print() vs. println()

java dev.to

Java Output Methods: Complete Guide to print() vs. println()

In Java, displaying output on the console is handled by the System.out stream. Understanding the operational difference between print() and println() is crucial for managing console layout and cursor positioning.


1. Overview of Output Methods

  • System.out.print(): Outputs the specified data to the console and keeps the cursor on the same line, immediately following the printed output.
  • System.out.println(): Outputs the specified data to the console and appends a newline character, moving the cursor to the beginning of the next line.
  • System.out.println() (Empty): Prints no text, serving purely to move the cursor down to a new line.

2. Practical Code Example

public class Num {
    public static void main(String[] args) {
        System.out.print(3 + 5);      // Line 1: Outputs 8, cursor stays on Line 1
        System.out.print(8 + 6);      // Line 1: Outputs 14 directly after 8
        System.out.println("");       // Line 1 -> Line 2: Moves cursor to Line 2
        System.out.println(6 + 7);    // Line 2: Outputs 13 on Line 2
    }
}
Enter fullscreen mode Exit fullscreen mode

3. Step-by-Step Execution Breakdown

Console Output

814
13
Enter fullscreen mode Exit fullscreen mode

Detailed Execution Flow

1.System.out.print(3 + 5):

Evaluates the expression: 3 + 5 = 8.

Prints 8 to the console.

Cursor Position: Remains on Line 1 directly after 8.

2.System.out.print(8 + 6):

Evaluates the expression: 8 + 6 = 14.

Prints 14 directly adjacent to 8.

Current Console View: 814

Cursor Position: Remains on Line 1 directly after 14.

3.System.out.println(""):

Outputs an empty string and triggers a line break.

Cursor Position: Moves down to the start of Line 2.

4.System.out.println(6 + 7):

Evaluates the expression: 6 + 7 = 13.

Prints 13 on Line 2.

Cursor Position: Moves down to Line 3.

Key Rule: print() leaves the cursor on the same line, while println() appends a newline immediately after writing its output.

Source: dev.to

arrow_back Back to Tutorials