Java Output

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

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 Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

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

Signed-in readers only.