
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:
java.lang package.out, which is of type PrintStream.out is a static reference variable within the System class.PrintStream class, which is responsible for outputting data to the console.PrintStream is a predefined class in the java.io package.print, println, and others.PrintStream class (in this case, the out reference).PrintStream class is created and stored in the heap memory area during program execution.PrintStream object.System.out.print("Hello"); calls the print method on the PrintStream object referenced by out.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:
print and println can output various data types (e.g., strings, integers, floats) without explicit conversion.System.out.println(); with no arguments prints a blank line.println when you want each piece of output to be visually separated.