In Java, print() and println() are methods of the PrintStream class used to display output on the console. Both methods print data such as strings, numbers, characters, and objects, but they differ in how they handle the cursor position after printing. Understanding their difference is important for formatting console output correctly.
- print() displays output and keeps the cursor on the same line.
- println() displays output and moves the cursor to the next line.
- Both methods are commonly used with System.out.
print() Method
print() method in Java is used to display a text on the console. This text is passed as the parameter to this method in the form of String. This method prints the text on the console and the cursor remains at the end of the text at the console.
- Prints output on the console.
- Cursor remains at the end of the printed text.
import java.io.*;
class GFG {
public static void main(String[] args)
{
// The cursor will remain
// just after the 1
System.out.print("GfG1");
// This will be printed
// just after the GfG2
System.out.print("Gf2");
}
}
Output
GfG1GfG2
println() Method
println() method in Java is also used to display a text on the console. This text is passed as the parameter to this method in the form of String. This method prints the text on the console and the cursor remains at the start of the next line at the console.
- Can be called with or without arguments.
- Helps improve output readability.
import java.io.*;
class GFG {
public static void main(String[] args)
{
// The cursor will after GFG1
// will at the start
// of the next line
System.out.println("GfG1");
// This will be printed at the
// start of the next line
System.out.println("GfG2");
}
}
Output
GfG1 GfG2
Example Demonstrating Both Methods
public class Main {
public static void main(String[] args) {
System.out.print("Hello");
System.out.println(" Java");
System.out.print("Welcome");
System.out.println(" Developers");
}
}
Output
Hello Java Welcome Developers
print() Vs println()
| Feature | print() | println() |
|---|---|---|
| Line Break | Does not add a new line | Adds a new line after printing |
| Cursor Position | Remains at end of current line | Moves to beginning of next line |
| Empty Call | Not allowed | Allowed (println()) |
| Output Format | Continuous output | Separate line output |
| Readability | Less readable for multiple outputs | More readable |
| Usage | Same-line printing | Line-by-line printing |
| Syntax | System.out.print(data); | System.out.println(data); |
| Newline Character | Not inserted | Automatically inserted |
| Common Use Case | Menus, formatted text, inline output | Messages, results, reports |
| Return Type | void | void |