The println() method of the PrintStream class in Java is used to print data to the output stream and then move the cursor to the beginning of the next line. When called without any arguments, it simply inserts a line break in the output stream.
- Belongs to the PrintStream class in the java.io package.
- Used to print a new line when called without parameters.
- Moves the cursor to the next line after printing.
import java.io.*;
class GFG {
public static void main(String[] args)
{
try {
// Create a PrintStream instance
PrintStream stream
= new PrintStream(System.out);
// Print the value 'GFG'
// to this stream using print() method
// This will put the in the
// stream till it is printed on the console
stream.print("GFG");
// Break the line in the stream
// using println() method
stream.println();
stream.flush();
}
catch (Exception e) {
System.out.println(e);
}
}
}
Output
GFG
Explanation: This program creates a PrintStream object connected to the console output stream and uses the print() method to display the text "GFG". The println() method is then called without any arguments to insert a line break and move the cursor to the next line.
Syntax
public void println()
- Parameters : None
- Return Value: This method does not return any value.
Example: Program to demonstrate PrintStream println() method
import java.io.*;
class GFG {
public static void main(String[] args)
{
try {
// Create a PrintStream instance
PrintStream stream
= new PrintStream(System.out);
// Print the value '1.65'
// to this stream using print() method
// This will put the in the
// stream till it is printed on the console
stream.print(1.65);
// Break the line in the stream
// using println() method
stream.println();
stream.flush();
}
catch (Exception e) {
System.out.println(e);
}
}
}
Output
1.65
Explanation of Example 2: In this example, the print() method displays the floating-point value 1.65 on the console without adding a new line. The println() method is subsequently used to break the line, ensuring that any further output starts from the next line.
Advantages of PrintStream println() Method in Java
- Automatically moves the cursor to the next line after printing.
- Makes console output more readable and well-organized.
- Eliminates the need to manually add newline characters (\n).
- Simplifies code by combining printing and line breaking in a single method.
- Supports printing different data types such as String, int, double, char, and boolean.
- Useful for displaying output in a structured, line-by-line format.
print() Vs println()
| Method | Behavior |
|---|---|
| print() | Prints data and keeps the cursor on the same line. |
| println() | Prints data (if provided) and moves the cursor to the next line. |
| println() (no arguments) | Only inserts a line break. |