Printing output in Java
System.out.println vs print vs printf, and System.err.
println vs print
System.out.println prints its text and then moves to a new line. System.out.print prints and stays on the same line, so the next output continues right after it.
System.out.print("A");
System.out.println("B");
System.out.print("C");
// Output:
// AB
// CYour turn
What does this print?
System.out.print("Ja");
System.out.println("va");
System.out.print("!");Ja va !Java !Java!
Show the answer
print("Ja") stays on the line, println("va") finishes the line, so ! starts a new one: Java then !.
printf fills in blanks
printf takes a format string with placeholders: %d for a whole number, %s for text, %.2f for a decimal with exactly two digits after the point, and %n for a new line.
System.out.printf("%s has %d coins%n",
"Ada", 3);
// Ada has 3 coinsYour turn
What does this print?
System.out.printf("Total: %.2f%n", 7.5);Total: 7.5Total: 7.50Total: %.2f
Show the answer
%.2f means "exactly two digits after the point", so 7.5 is shown as 7.50. %n ends the line.
Width and alignment
A number after % sets a minimum width. %5d pads with spaces on the left (right-aligned). %-5d pads on the right (left-aligned). %05d pads with zeros. Great for neat tables.
System.out.printf("[%5d]%n", 7); // [ 7]
System.out.printf("[%-5d]%n", 7); // [7 ]
System.out.printf("[%05d]%n", 7); // [00007]Where do errors go?
System.out.println("Error: no file");Goes into the same stream as normal output. Redirect output to a file and the error vanishes into it.
System.err.println("Error: no file");System.err is a separate stream, so errors still reach the screen when normal output is redirected.
In real projects
Servers and containers capture standard output and standard error separately, and monitoring tools often watch stderr for trouble. printf-style formatting shows up everywhere: String.format, log messages, invoices and reports.
Key takeaways
- println adds a newline, print doesn't
- printf("%d %s %.2f%n", …) formats values; %n is a newline
- System.err is for errors, so they can be redirected separately
%n prints the platform's own line separator (\r\n on Windows, \n on macOS and Linux), while \n is always a single line-feed character.
Practice questions
What does this print?
System.out.print("A");
System.out.println("B");
System.out.print("C");- A B C
- AB C
- ABC
- A BC
Check your answer
AB C. print("A") stays on the line, println("B") finishes the line with a newline, then C starts a new line.
What does this print?
System.out.printf("%d items: %.2f%n", 3, 4.5);- 3 items: 4.5
- %d items: %.2f
- 3 items: 4.500000
- 3 items: 4.50
Check your answer
3 items: 4.50. %d is replaced by the int 3 and %.2f formats 4.5 with exactly two digits after the decimal point. %n ends the line.