image.png


Working of the Print Statement in Java

The print statement in Java is a fundamental way to display output on the console, which is the command-line interface (CLI). In Java, printing is achieved using methods like System.out.print or System.out.println. Let’s break down how this works:

In summary, when you write System.out.print("Hello");, the System class provides access to the out variable, which in turn invokes the print method on the PrintStream object to display "Hello" on the console.


Difference Between print and println Methods

The print and println methods both belong to the PrintStream class and are used to output data to the console, but they differ in their behavior. Below is a detailed comparison in tabular format, including five points for each method with examples:

Feature print Method println Method
Cursor Position Leaves the cursor on the same line after printing. Moves the cursor to the next line after printing.
New Line Character Does not append a newline character (\n) at the end of the output. Automatically appends a newline character (\n) at the end of the output.
Usage Ideal for printing multiple items or continuous text on the same line. Ideal for printing text that should appear on separate lines.
Output Continuity Subsequent output continues immediately after the previous output on the same line. Subsequent output starts on a new line, making it easier to separate content.
Flexibility Useful for building custom output formats (e.g., comma-separated values). Convenient for quick, readable output where each statement stands alone.
Example 1 `System.out.print("Hello");
System.out.print(" World");`
Output: Hello World `System.out.println("Hello");
System.out.println("World");`
Output:
Hello
World

Additional Notes: