Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 201 ยท Getting Started

Printing Output

Print output in Java with System.out.println, print and IO.println, use escape sequences like \n and \t, format numbers with printf, and send errors to System.err.

Printing is how a program talks to you. It's how you see results, follow what your code is doing, and spot bugs. Java gives you a small, dependable toolkit for it: println and print for plain output, escape sequences for special characters like tabs and line breaks, printf for neatly formatted numbers, and a separate error stream for problems.

This lesson covers each of these, with the details that matter in practice: what + does when you mix text and numbers, why %n is better than \n in printf, and the mistakes that make formatted output crash.

println and print

You've already used println, which prints a value and then ends the line. Its sibling print prints the value and stays on the same line, so the next output continues right after it. Java offers both in two places:

  • System.out.println and System.out.print work in every Java version and appear in nearly all existing code.
  • IO.println and IO.print were added in Java 25 as a shorter alternative, together with compact source files.
Java println vs print

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Calling println() with nothing inside prints just a line break, which is the easy way to get a blank line. (print() with nothing inside doesn't exist; it has nothing to print.)

Both families print to the same place, the standard output stream, so you can mix them freely. In this course, short demos often use IO.println and classic programs use System.out.println, so you'll be fluent in both.

Printing different kinds of values

println accepts any value: text, whole numbers, decimals, true/false, single characters, and objects. Each is converted to text automatically:

Java Printing all kinds of values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Two results deserve a second look. 3.0 prints as 3.0, not 3, because it's a decimal (double) value. And 0.1 + 0.2 prints 0.30000000000000004: computers store decimals in binary, so tiny rounding errors appear. That's not a Java bug; it happens in almost every language. You'll learn when it matters, and how printf and BigDecimal help, in Working with Numbers.

Objects such as lists and dates print in a readable form because their classes define a toString method. Arrays are an exception: printing an int[] gives something cryptic like [I@6d06d69c. Use Arrays.toString(array) instead, as shown in Arrays.

Joining text with +

The + operator joins strings together, and if either side of + is a string, the other side is converted to text. This is called string concatenation, and it has one famous trap: Java evaluates + from left to right.

Java Concatenation goes left to right

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Here's what happened:

  • "Total: " + apples + pears is read as ("Total: " + 3) + 4. The first + makes the string "Total: 3", so the second + appends "4", giving Total: 34.
  • With parentheses, apples + pears is calculated first, giving Total: 7.
  • apples + pears + " pieces of fruit" prints 7 pieces of fruit, because the numbers are added before any string appears.
  • 'A' + 'B' prints 131. Characters are numbers underneath (A is 65, B is 66), so adding two chars is arithmetic. Characters and Booleans explains why.

Tip: Whenever you put a calculation inside a printed message, wrap it in parentheses. It costs two characters and avoids the whole class of bugs above.

Escape sequences

Some characters can't be typed directly inside a string. You can't put a raw line break or an unescaped double quote between quotes, for example. Escape sequences solve this: a backslash \ followed by a character that stands for something special.

Escape Meaning
\n New line (line feed)
\t Tab
\" Double quote
\' Single quote (needed in char literals: '\'')
\\ Backslash
\s A single space (Java 15+, mostly useful in text blocks)
\r Carriage return (part of Windows line endings)
\b, \f Backspace, form feed: terminal control codes you'll rarely need
Java Escape sequences

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

A few notes:

  • Tabs jump to the next tab stop (usually every 8 columns), so they only line columns up when every value is short. For reliable alignment, use printf widths instead (next section).
  • Inside a string, a single quote doesn't need escaping. Inside a char literal, a double quote doesn't either: '"' is fine.
  • A backslash followed by a character that isn't a valid escape, such as "C:\Program", is a compile error: illegal escape character. Double the backslash, or use forward slashes, which Java accepts in file paths on Windows too.

For multi-line text, Java also has text blocks written between triple quotes """. They're perfect for longer messages, JSON or SQL, and they're covered in Text Blocks and Escape Sequences.

Formatted output with printf

When you need numbers with a fixed number of decimals or values lined up in columns, use System.out.printf. Its first argument is a format string containing placeholders called format specifiers, which start with %. The values that follow fill them in, in order:

Java printf basics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The specifiers you'll use most:

Specifier Formats Example Output
%s anything, as text printf("%s", "hi") hi
%d whole numbers (int, long) printf("%d", 42) 42
%f decimals, 6 places by default printf("%f", 2.5) 2.500000
%.2f decimals, 2 places (rounded) printf("%.2f", 2.678) 2.68
%n a line break printf("a%nb") two lines
%% a literal percent sign printf("50%%") 50%
%c, %b a character, a boolean printf("%c %b", 'x', true) x true

Use %n for line breaks in printf. Unlike println, printf doesn't end the line for you. %n produces the correct line separator for the operating system the program runs on, while \n is always a single line-feed character. Both work in our editor, but %n is the professional habit.

Widths and alignment

A number between % and the letter sets a minimum width: the value is padded with spaces to fill it. Values are right-aligned by default; a minus sign aligns them left. That's how you print tidy tables:

Java Lining up a table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

  • %-10s prints text left-aligned in 10 columns, and %5d a number right-aligned in 5.
  • %8.2f combines both ideas: at least 8 columns wide, 2 decimals.
  • %05d pads with zeros (00042), %,d adds thousands separators (1,234,567), and %x prints hexadecimal (ff).

Formatting Strings covers every flag, dates, and locale-aware formatting.

Building formatted strings

IO has no printf. When you want a formatted string, to print with IO.println or to store in a variable, use String.format or the formatted method. Both use exactly the same specifiers:

Java
String line = String.format("%-8s %6.2f", "Tea", 2.5);
String same = "%-8s %6.2f".formatted("Tea", 2.5);
IO.println(line);

Note: printf follows the computer's locale. Our server uses US English, so %,.2f prints 1,234.50. On a computer set to German it prints 1.234,50. When output must look the same everywhere (files, logs, data for other programs), pass a locale explicitly: String.format(Locale.ROOT, "%.2f", value).

When printf goes wrong

The format string is only checked when the program runs, and mistakes throw exceptions:

Java printf mistakes (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first line works. The second throws IllegalFormatConversionException: d != java.lang.Double, because %d only accepts whole numbers; use %f or %.1f for decimals. Notice that Average: was already printed before the crash: printf writes the format string piece by piece and fails only when it reaches the bad specifier. Similarly, too few values for the placeholders causes a MissingFormatArgumentException. Extra values, on the other hand, are silently ignored, which can hide bugs. IDEs warn about all of these as you type.

The error stream: System.err

Besides standard output, every program has a second stream for error messages: System.err. It has the same methods as System.out (println, print, printf):

Java Normal output and errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Why have two streams? On the command line you can send them to different places. For example, java App.java > results.txt saves normal output to a file while errors still appear on screen, so warnings never corrupt your data. Exception messages and stack traces are printed to System.err too.

In our editor, error output appears in red, after all the normal output, because the two streams are collected separately. That's why the warning above shows up last even though it was printed second. In a terminal, the lines would usually appear in the order they were printed.

Tip: println is perfect for learning and small tools. Real applications use a logging library instead, which adds timestamps and severity levels and can be switched on or off without changing code. See Logging.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does System.out.println("Sum: " + 2 + 3); print?

    + works left to right. "Sum: " + 2 is the string "Sum: 2", and adding 3 appends "3". Write "Sum: " + (2 + 3) to get Sum: 5.
  2. 2. What does this print? System.out.print("A"); System.out.println("B"); System.out.print("C");

    print stays on the line, so B follows A. println then ends the line, so C starts a new one.
  3. 3. Which line prints Price: 4.50?

    %.2f always shows two decimals. %d throws an exception for a double, and both %s and string concatenation print 4.5, because the value 4.50 is the same number as 4.5.
  4. 4. How do you print the text He said "hi" with println?

    Inside a string, a double quote must be escaped as \". Without the backslash, the quote ends the string. Single quotes are only for single characters in Java.
  5. 5. In printf, why prefer %n over \n?

    %n uses the platform's line separator (\r\n on Windows, \n elsewhere). \n still works, but it is always a single line-feed character.

Summary

  • println prints a value and ends the line; print stays on the same line; println() prints a blank line.
  • System.out.println works everywhere; IO.println and IO.print are Java 25's shorter versions. Both write to standard output.
  • With +, a string on either side means concatenation, evaluated left to right: wrap calculations in parentheses.
  • Escape sequences: \n new line, \t tab, \" quote, \\ backslash, \' single quote.
  • printf formats values: %s, %d, %.2f, %n, %%, widths like %-10s and %8.2f. Wrong specifiers throw at run time.
  • String.format and "...".formatted(...) build formatted strings without printing.
  • System.err is a separate stream for errors and warnings; in our editor it appears in red after normal output.

Next: Reading User Input, where your programs start asking questions and reacting to the answers.