Java Output

Su Suriya Ravichandran Updated 14 Nov 2026
6 min read ·Lesson 6 of 133

Printing to the console is the first way any program communicates. Java routes console output through System.out, a PrintStream object connected to standard output. Everything below builds on that single object.

System.out.println()

println prints its argument followed by a newline.

System.out.println("Hello, World!");
System.out.println(42);
System.out.println(3.14);
System.out.println(true);
System.out.println('A');
System.out.println();          // prints only a newline

Output:

Hello, World!
42
3.14
true
A

println is overloaded: there is a version for each primitive type, one for String, one for char[], and one for Object. The compiler picks the right one from the argument type, so you never need to convert a number to a string before printing it.

Breaking down the call

  • System is a final class in java.lang holding system-level resources.
  • out is a public static final PrintStream field of System. Being static, it is accessed through the class name, not an instance.
  • println is an instance method of PrintStream.

System.err is a second PrintStream for error messages. Terminals usually show both in the same window, but they are separate streams: a shell can redirect them independently (java App > log.txt 2> errors.txt), and build tools and loggers treat System.err output as errors. Use System.err.println for diagnostics and failures.

System.out.print()

print is identical to println except that it does not add a newline.

System.out.print("Loading");
System.out.print("...");
System.out.print("done");
System.out.println();

Output:

Loading...done

The cursor stays at the end of the printed text, so the next output continues on the same line. This is useful for building a line in pieces, for progress indicators, or for prompts where the user's input should appear on the same line as the prompt text.

Printing Expressions and Concatenation

Any expression can be printed. When a String is combined with +, the other operand is converted to text.

int apples = 3;
int oranges = 5;

System.out.println("Total fruit: " + (apples + oranges));
System.out.println("Total fruit: " + apples + oranges);

Output:

Total fruit: 8
Total fruit: 35

The second line looks wrong but is correct. + is evaluated left to right. "Total fruit: " + apples produces the string "Total fruit: 3"; then + oranges appends "5". Once one operand is a String, every subsequent + is string concatenation. Parentheses force the arithmetic to happen first.

Printing an object calls its toString() method:

import java.util.List;

List<String> names = List.of("Ada", "Linus");
System.out.println(names);          // [Ada, Linus]

Object o = new Object();
System.out.println(o);              // java.lang.Object@1b6d3586 (hash code varies)

List has a readable toString. A plain Object does not, and prints its class name and identity hash. Classes you write should override toString if they are ever printed; records do this automatically.

System.out.printf() and Formatted Output

printf prints a format string in which placeholders are replaced by the following arguments. It gives control over decimal places, padding, alignment, and number formatting that concatenation cannot provide.

String name = "Ada";
int age = 36;
double balance = 1234.5;

System.out.printf("Name: %s, Age: %d, Balance: %.2f%n", name, age, balance);

Output:

Name: Ada, Age: 36, Balance: 1234.50

Each % placeholder is a format specifier. Arguments are matched to specifiers in order.

Common format specifiers

SpecifierType expectedOutput
%dinteger (int, long, ...)Decimal integer
%ffloating pointDecimal number, default 6 places
%.2ffloating point2 decimal places
%sanyString.valueOf(arg)
%ccharSingle character
%banytrue/false
%efloating pointScientific notation
%xintegerHexadecimal
%,dintegerThousands separators (1,234,567)
%%noneLiteral %
%nnonePlatform newline

Passing an argument of the wrong type throws IllegalFormatConversionException at runtime. %d with a double fails; %s accepts anything.

Width and alignment

A number between % and the type letter sets the minimum width. The output is right-aligned by default; a - flag left-aligns. 0 pads numbers with leading zeros.

System.out.printf("[%5d]%n", 42);      // [   42]
System.out.printf("[%-5d]%n", 42);     // [42   ]
System.out.printf("[%05d]%n", 42);     // [00042]
System.out.printf("[%8.3f]%n", 3.14159); // [   3.142]
System.out.printf("[%-10s]%n", "left"); // [left      ]

This is how tabular console output is produced:

String[] items = {"Keyboard", "Mouse", "Monitor"};
double[] prices = {49.99, 19.5, 229.0};

System.out.printf("%-10s %8s%n", "Item", "Price");
for (int i = 0; i < items.length; i++) {
    System.out.printf("%-10s %8.2f%n", items[i], prices[i]);
}

Output:

Item          Price
Keyboard      49.99
Mouse         19.50
Monitor      229.00

%-10s reserves 10 characters, left-aligned, for the name; %8.2f reserves 8 characters, right-aligned, with two decimals, so the decimal points line up.

%n versus \n

\n is always a line-feed character. %n in a format string produces the platform's line separator (\r\n on Windows, \n elsewhere). For console output the difference rarely matters, but for files that will be opened on Windows %n or System.lineSeparator() gives the expected result.

System.out.format(...) is an exact synonym of printf.

String.format()

The same formatting is available without printing. String.format returns the formatted text as a String:

String line = String.format("%-10s %8.2f", "Monitor", 229.0);
System.out.println(line);

Since Java 15, the instance method formatted does the same with the format string as the receiver:

String greeting = "Hello, %s! You have %d new messages.".formatted("Ada", 3);

Use these when the formatted text goes somewhere other than the console: a log message, a file, a GUI label, an HTTP response.

Escape Sequences

Inside a string literal, a backslash introduces a character that cannot be typed directly.

SequenceMeaning
\nNewline
\tTab
\"Double quote
\'Single quote
0Backslash
\rCarriage return
\uXXXXUnicode character by hex code
System.out.println("Line one\nLine two");
System.out.println("Name:\tAda");
System.out.println("She said \"hello\"");
System.out.println("C:\\Users\\ada");
System.out.println("Caf\u00e9");

Output:

Line one
Line two
Name:   Ada
She said "hello"
C:\Users\ada
Café

Multi-Line Output with Text Blocks

For several lines of output, a text block (Java 15+) avoids repeated println calls and escape sequences. It starts with """ followed by a newline and ends with """.

String menu = """
        1. Start game
        2. Load game
        3. Quit
        """;
System.out.print(menu);

Output:

1. Start game
2. Load game
3. Quit

The common leading indentation is removed automatically, determined by the position of the closing """ or the least-indented line. Text blocks are covered in full in the Strings section.

Printing Arrays

Printing an array directly does not print its contents:

int[] nums = {1, 2, 3};
System.out.println(nums);                    // [I@6d06d69c
System.out.println(Arrays.toString(nums));   // [1, 2, 3]

Arrays do not override toString, so the default Object version prints a type code and hash. java.util.Arrays.toString produces a readable form; Arrays.deepToString handles nested arrays.

Flushing and Buffering

System.out is buffered: output may be held briefly before reaching the terminal. println triggers a flush when the stream is in autoflush mode, which is the default for System.out, so console output appears immediately. If output seems to be missing when a program crashes or is killed, call System.out.flush() explicitly before the risky operation.

When printing large volumes (hundreds of thousands of lines), System.out.println is slow because of per-call synchronization and flushing. Wrapping standard output in a BufferedWriter or PrintWriter with a large buffer and flushing once at the end is dramatically faster:

import java.io.PrintWriter;

PrintWriter out = new PrintWriter(System.out, false);
for (int i = 0; i < 1_000_000; i++) {
    out.println(i);
}
out.flush();

The false argument disables autoflush. Nothing reaches the terminal until flush() is called, which is exactly what makes it fast.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining
Ask about this post
AI Ask about this post

Ask questions about Java Output and get answers drawn from it.

Signed-in readers only.