Output in Java
Introduction
In Java, output refers to displaying messages or results to the screen. Java provides System.out.print() and System.out.println() to send output to the console.
What is System.out?
- System is a predefined class in the java.lang package.
- out is a static object of the PrintStream class within System.
- So, System.out allows us to call methods to print text to the console.
1. System.out.println() – Print with Line Break
This method prints the content and then moves the cursor to a new line.
Example:
public class Main {
public static void main(String[] args) {
int age = 22;
String name = "Simran";
System.out.println(name + " is " + age + " years old.");
System.out.println("Shiksha");
System.out.println("Sanchar");
System.out.println(); // Prints an empty line
}
}
Output:
Simran is 22 years old.
Shiksha
Sanchar
Explanation:
System.out.println(name + " is " + age + " years old.");→ Combines strings and variables using+and prints the full sentence with proper spacing.- Each System.out.println() prints on a new line.
- System.out.println(); prints an empty line for spacing or formatting.
2. System.out.print() – Print Without Line Break
This method prints the content and stays on the same line.
Example:
public class Main {
public static void main(String[] args) {
System.out.print("Shiksha");
System.out.print("Sanchar");
}
}
Output:
ShikshaSanchar
Explanation:
System.out.print("Shiksha");→ Prints "Shiksha" and keeps the cursor on the same line.System.out.print("Sanchar");→ Immediately prints "Sanchar" right after "Shiksha", without moving to a new line.- So, both outputs appear on a single line without any space between them.
Note: If you want a space between "Shiksha" and "Sanchar", you should add it manually like this:
System.out.print("Shiksha ");
System.out.print("Sanchar");
Summary:
| Concept | Description |
|---|---|
| System.out | Sends output to the console |
| System.out.println() | Prints text and moves to the next line |
| System.out.print() | Prints text on the same line |