Java Output
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
Systemis a final class injava.langholding system-level resources.outis apublic static final PrintStreamfield ofSystem. Being static, it is accessed through the class name, not an instance.printlnis an instance method ofPrintStream.
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
| Specifier | Type expected | Output |
|---|---|---|
%d | integer (int, long, ...) | Decimal integer |
%f | floating point | Decimal number, default 6 places |
%.2f | floating point | 2 decimal places |
%s | any | String.valueOf(arg) |
%c | char | Single character |
%b | any | true/false |
%e | floating point | Scientific notation |
%x | integer | Hexadecimal |
%,d | integer | Thousands separators (1,234,567) |
%% | none | Literal % |
%n | none | Platform 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.
| Sequence | Meaning |
|---|---|
\n | Newline |
\t | Tab |
\" | Double quote |
\' | Single quote |
|