Print Multiple Lines in Java
Problem
Each call to System.out.println() automatically adds a newline after the text it prints, so multiple calls appear on separate lines.
Print three separate lines of text to the console.
Java Program
public class PrintMultipleLines {
public static void main(String[] args) {
System.out.println("Line 1");
System.out.println("Line 2");
System.out.println("Line 3"); // each call starts on a fresh line
}
}Output
Core Logic
Calling println() once per line is the most direct way to print several lines — each call ends with its own newline.
- 1The first
println("Line 1")prints the text and moves the cursor to a new line. - 2The next
println()call starts writing from that new line, and does the same again. - 3Repeating the call for each line builds up the full multi-line output.
println() calls produce three separate lines in the console, in the order they were called.Key Point: print() (without ln) would leave the cursor on the same line — the "ln" in println is what adds the newline automatically.
Key Concepts
Approach 2: Java 8
import java.util.List;
public class PrintMultipleLinesForEach {
public static void main(String[] args) {
// System.out::println is shorthand for line -> System.out.println(line)
List.of("Line 1", "Line 2", "Line 3").forEach(System.out::println);
}
}
Output
Core Logic
The three separate println() calls can collapse into one — collect the lines into a list and hand printing off to forEach().
- 1
List.of("Line 1", "Line 2", "Line 3")creates an immutable list holding all three lines. - 2
.forEach(System.out::println)callsprintlnonce per element, using a method reference instead of writing three separate statements. - 3Each call to
printlnstill adds its own newline, exactly as it did when written out by hand.
forEach(System.out::println) visits "Line 1", then "Line 2", then "Line 3", printing each on its own line in list order.Key Point: System.out::println is a method reference — shorthand for the lambda line -> System.out.println(line) — and reads cleanly here because forEach hands each element straight to a method that already accepts exactly one argument.
Key Concepts
Interview Questions
How do you print a newline inside a single string?
Use the escape \n, or %n with printf, which uses the operating system's line separator.
What's the difference between print and println?
println adds a line break after the text; print doesn't.