Java Console Output: println, printf and String.format
Introduction
Printing to the console is the first way every Java programmer sees their program's results. This tutorial explains console output in Java with println, print, printf and String.format. We will start with
(Note - This tutorial uses the escape sequences, such as
OUTPUT of the above code
Explanation of the code
Formatted output with printf()
Syntax of a format specifier
Where,
OUTPUT of the above code
Explanation of the code
Printing a table with width and alignment
Widths and alignment make it easy to print columns which line up -
OUTPUT of the above code
The text column is left-aligned with
OUTPUT of the above code
Standard error - System.err
Besides
Use
println() and print(), and how they print values of any type. We will then format numbers, text and tables precisely with printf() and its format specifiers. Next we will build formatted strings with String.format() and formatted(). Lastly, we will look at the standard error stream, System.err.(Note - This tutorial uses the escape sequences, such as
\n and \t, covered in Java LiteralsClick to read tutorial: Java Literals: Integer, Floating-Point, char and boolean.)
println() and print()
System.out is a PrintStream connected to the console. Its two simplest methods are -println(x)- printsxand then moves to a new line.println()with no argument prints just an empty line.print(x)- printsxand stays on the same line.
toString() method.
println() and print()
//PrintDemo.java
import java.time.LocalDate;
import java.util.List;
public class PrintDemo {
public static void main(String[] args) {
System.out.print("Loading");
System.out.print(".");
System.out.print(".");
System.out.println(" done");
System.out.println();
System.out.println(42);
System.out.println(3.75);
System.out.println('J');
System.out.println(true);
System.out.println(List.of("Tom", "Harry"));
System.out.println(LocalDate.of(2026, 10, 22));
char[] letters = {'J', 'a', 'v', 'a'};
System.out.println(letters);
System.out.println("Price: " + 19.99 + ", qty: " + 3);
}
}
Loading.. done 42 3.75 J true [Tom, Harry] 2026-10-22 Java Price: 19.99, qty: 3
- The
print()calls built up one line, whichprintln()ended. The emptyprintln()printed a blank line. - A
Listand aLocalDateprinted readable text, from theirtoString()methods. - A
chararray is a special case -println()prints its characters as a word. - Joining values with
+is the simplest way to build a line of output, but it gives no control over things like decimal places. That is whatprintf()is for.
printf() takes a format string followed by values. Each format specifier in the format string, starting with %, is replaced by the next value, formatted as the specifier says.Syntax of a format specifier
%[flags][width][.precision]conversionconversionis the type of value:dfor integers,ffor decimal numbers,efor scientific notation,sfor strings (and any object),cfor characters,bfor booleans,xfor hexadecimal, andnfor a new line.widthis the minimum number of characters to print. Values are right-aligned in that width by default..precisionis the number of digits after the decimal point forfande, or the maximum number of characters fors.flagschange the formatting:-left-aligns,0pads with zeros,,adds thousands separators,+always shows the sign.
printf() format specifiers
//PrintfDemo.java
public class PrintfDemo {
public static void main(String[] args) {
String name = "Tom";
int age = 32;
double salary = 85432.5;
System.out.printf("%s is %d years old.%n", name, age);
System.out.printf("Salary: %.2f%n", salary);
System.out.printf("Salary: %,.2f%n", salary);
System.out.printf("Pi to 4 places: %.4f%n", Math.PI);
System.out.printf("Scientific: %e%n", 123456.789);
System.out.printf("Order no: %06d%n", 42);
System.out.printf("Change: %+d%n", 15);
System.out.printf("Hex: %x, char: %c, boolean: %b%n", 255, 'J', true);
System.out.printf("Discount: 15%%%n");
System.out.printf("[%8s] [%-8s] [%.3s]%n", name, name, "JavaBrahman");
}
}
Tom is 32 years old. Salary: 85432.50 Salary: 85,432.50 Pi to 4 places: 3.1416 Scientific: 1.234568e+05 Order no: 000042 Change: +15 Hex: ff, char: J, boolean: true Discount: 15% [ Tom] [Tom ] [Jav]
%nprints the correct line separator for the operating system. Unlikeprintln(),printf()does not add a new line itself.%.2frounds to two decimal places, and%,.2falso adds thousands separators.%06dpads to width 6 with leading zeros, and%+dshows a+for positive numbers.%%prints a literal percent sign.%8sright-aligns in 8 characters,%-8sleft-aligns, and%.3skeeps only the first 3 characters.- Using the wrong conversion for a value, such as
%dwith adouble, throws anIllegalFormatConversionExceptionat runtime.
%,.2f prints 85.432,50. To get a fixed format regardless of where the program runs, pass a locale - System.out.printf(Locale.US, "%,.2f%n", salary).
Printing an aligned table with printf()
//InvoiceTable.java
public class InvoiceTable {
public static void main(String[] args) {
String[] items = {"Java book", "USB cable", "Laptop stand"};
int[] quantities = {2, 10, 1};
double[] prices = {39.5, 4.25, 1249.0};
System.out.printf("%-14s %5s %10s%n", "Item", "Qty", "Amount");
System.out.println("-".repeat(31));
double total = 0;
for (int i = 0; i < items.length; i++) {
double amount = quantities[i] * prices[i];
total += amount;
System.out.printf("%-14s %5d %,10.2f%n", items[i], quantities[i], amount);
}
System.out.println("-".repeat(31));
System.out.printf("%-14s %5s %,10.2f%n", "Total", "", total);
}
}
Item Qty Amount ------------------------------- Java book 2 79.00 USB cable 10 42.50 Laptop stand 1 1,249.00 ------------------------------- Total 1,370.50
%-14s, while the number columns are right-aligned so that their digits and decimal points line up. (Loops and arrays are covered in detail later in this series.)
Building strings with String.format() and formatted()
String.format() works exactly like printf(), but returns the formatted text as a String instead of printing it - ready to store, log, or show in a user interface. Since Java 15, the formatted() method does the same, called on the format string itself.
String.format() and formatted()
//FormatDemo.java
public class FormatDemo {
public static void main(String[] args) {
String label = String.format("%s: %.1f%%", "Progress", 72.456);
System.out.println(label);
System.out.println("Length of label: " + label.length());
String receipt = "Order #%05d - %d items - %.2f".formatted(317, 3, 98.5);
System.out.println(receipt);
String time = String.format("%02d:%02d:%02d", 9, 5, 7);
System.out.println("Time: " + time);
}
}
Progress: 72.5% Length of label: 15 Order #00317 - 3 items - 98.50 Time: 09:05:07
System.out, every program has a second output stream, System.err, for error messages. Both normally appear in the console, but they can be sent to different places - for example, when a program's output is redirected to a file, its error messages still appear on screen. IDEs usually show System.err output in red.
Printing an error message
System.err.println("Error: the input file could not be found");
System.err for error messages in small programs. Larger applications use a logging library instead of printing directly.
Summary
In this tutorial we first printed values of every type with println() and print(). We then formatted output with printf(), using the conversions %d, %f, %s and others, with widths, precisions and flags, and printed an aligned table. Next we built formatted strings with String.format() and formatted(). Lastly, we saw System.err, the stream for error messages. In the next tutorial, we will go the other way and read input from the user with ScannerClick to read tutorial: Reading User Input in Java with Scanner.Java Fundamentals Tutorials
Java Operator Precedence and Associativity ExplainedClick to read tutorial: Java Operator Precedence and Associativity Explained Reading User Input in Java with ScannerClick to read tutorial: Reading User Input in Java with Scanner Java Syntax Basics: Statements, Identifiers, KeywordsClick to read tutorial: Java Syntax Basics: Statements, Identifiers, Keywords Variables in Java: Declaration, Initialization and ScopeClick to read tutorial: Variables in Java: Declaration, Initialization and Scope Java Primitive Data Types and Their Ranges with ExamplesClick to read tutorial: Java Primitive Data Types and Their Ranges with Examples Java Literals: Integer, Floating-Point, char and booleanClick to read tutorial: Java Literals: Integer, Floating-Point, char and boolean Type Conversion and Casting in Java with ExamplesClick to read tutorial: Type Conversion and Casting in Java with Examples
Java Operator Precedence and Associativity ExplainedClick to read tutorial: Java Operator Precedence and Associativity Explained Reading User Input in Java with ScannerClick to read tutorial: Reading User Input in Java with Scanner Java Syntax Basics: Statements, Identifiers, KeywordsClick to read tutorial: Java Syntax Basics: Statements, Identifiers, Keywords Variables in Java: Declaration, Initialization and ScopeClick to read tutorial: Variables in Java: Declaration, Initialization and Scope Java Primitive Data Types and Their Ranges with ExamplesClick to read tutorial: Java Primitive Data Types and Their Ranges with Examples Java Literals: Integer, Floating-Point, char and booleanClick to read tutorial: Java Literals: Integer, Floating-Point, char and boolean Type Conversion and Casting in Java with ExamplesClick to read tutorial: Type Conversion and Casting in Java with Examples