Sub topic 8
Console I/O with java.lang.IO
This chapter covers the java.lang.IO class. It gives small programs simple console input and output without the System.out and Scanner boilerplate. It assumes you can run a compact source file with java File.java. It also assumes you know how Integer.parseInt and String.format work.
Why a new class for console I/O
A first program that talks to the user needs three things in the traditional style: System.out.println for output, a Scanner (imported from java.util) wrapped around System.in for input, and a decision about closing the scanner. Each of these is a detour for a beginner.
java.lang.IO removes the detour. It is a final class with only static methods, so you call it without creating an object. It lives in the java.lang package, so it is available in every Java source file without an import. It is not limited to compact source files. A traditional class can call IO.println too.
The API
The class has five methods.
| Method | What it does |
|---|---|
| `IO.println(Object obj)` | Prints the text form of `obj`, then a line terminator |
| `IO.println()` | Prints only a line terminator |
| `IO.print(Object obj)` | Prints the text form of `obj` with no line terminator |
| `IO.readln()` | Reads one line from standard input and returns it as a `String` |
| `IO.readln(String prompt)` | Prints `prompt`, then reads one line |
The output methods take an Object. A primitive argument such as 42 is boxed automatically, and any object is converted with String.valueOf. That is why IO.println(new Point(1, 2)) prints Point[x=1, y=2].
The returned line does not include the line terminator.
Output
void main() {
IO.println("Hello, world!");
IO.print("No newline here. ");
IO.print(42);
IO.println();
IO.println(3.5);
IO.println(List.of(1, 2, 3));
}This prints:
Hello, world!
No newline here. 42
3.5
[1, 2, 3]List needs no import here because a compact source file imports the java.base packages automatically.
Formatting
IO has no printf equivalent. Build the string first and pass it in. Use String.format or the formatted method on a string.
void main() {
double price = 19.989;
IO.println("Price: %.2f".formatted(price));
IO.println(String.format("%-8s|%5d|", "left", 42));
}Output:
Price: 19.99
left | 42|Input
IO.readln blocks until the user enters a line, then returns it as a String. The version with a prompt is the one you will use most.
void main() {
String name = IO.readln("Your name: ");
IO.println("Hello, " + name + "!");
}The prompt is printed exactly as given. Include the trailing space yourself, as in "Your name: ", because IO does not add one.
Reading numbers
readln always returns text. To read a number, convert it yourself. Trim the input first, since users often add spaces.
void main() {
String text = IO.readln("How old are you? ").trim();
int age = Integer.parseInt(text);
IO.println("Next year you will be " + (age + 1) + ".");
}If the user types abc, Integer.parseInt throws a NumberFormatException. For a script, that stack trace may be acceptable. For anything friendlier, catch the exception and ask again:
int readInt(String prompt) {
while (true) {
String text = IO.readln(prompt).trim();
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
IO.println("Please enter a whole number.");
}
}
}
void main() {
int a = readInt("First number: ");
int b = readInt("Second number: ");
IO.println(a + " + " + b + " = " + (a + b));
}readInt is a top-level method, so it becomes an instance method of the implicit class. The main method calls it like any other member.
What happens at end of input
When standard input has no more data, readln returns null. This happens when the user presses Ctrl+D (Ctrl+Z then Enter on Windows). It also happens when input is piped from a file or another command and runs out. A loop that reads until the end must check for null.
void main() {
int total = 0;
int count = 0;
String line;
while ((line = IO.readln()) != null) {
if (line.isBlank()) {
continue;
}
total += Integer.parseInt(line.trim());
count++;
}
IO.println("Read " + count + " numbers, total " + total);
}Without the null check, the first call after the data ends would return null, and the next method call on it would throw a NullPointerException.
You can test this program by piping input into it:
printf '10\n20\n\n30\n' | java Sum.javaIt prints Read 3 numbers, total 60.
How the pieces fit
All five methods work on the program's console. Output goes to the same place as System.out. Input comes from the same place as System.in. Mixing the two styles in one program is allowed, but be careful with input. IO.readln and a Scanner on System.in can each buffer data the other then never sees. Pick one input style per program.
Comparison with the traditional approach
The following program is the traditional way to do what IO.readln does.
import java.util.Scanner;
public class Greet {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Your name: ");
String name = in.nextLine();
System.out.println("Hello, " + name + "!");
}
}The two differ in a few ways that matter.
Scanner.nextLinethrowsNoSuchElementExceptionat end of input.IO.readlnreturnsnull.Scannercan parse numbers and tokens (nextInt,next).IOreads whole lines only.Scanneroffers many options such as delimiters and locales.IOoffers none.Scannerneeds an import.IOdoes not.
Use IO for small programs and teaching examples. Use Scanner, BufferedReader, or Console directly when you need tokenizing, a specific charset, or tight control of a stream.
Common pitfalls
- Forgetting that
readlnreturns text.IO.readln("n: ") + 1concatenates, so typing5gives"51". Convert withInteger.parseIntfirst. - Skipping the
nullcheck in a loop. A read-until-empty loop ends only onnull, not on an empty string. An empty line is a valid line. - Expecting formatting methods.
IO.println("%d", 5)does not compile, becauseprintlntakes one argument. Use"%d".formatted(5). - Shadowing the name. If you declare your own class or top-level member named
IOin the same file, it hidesjava.lang.IO. Choose another name. - Using Java 24 or earlier. In earlier previews the class was
java.io.IOand needed an explicitimport static java.io.IO.*;to call methods without theIO.prefix. In Java 25 it isjava.lang.IO, and you always call it asIO.println.
Using IO in a traditional class
Because IO is in java.lang, you can use it in a full class with no compact source features:
public class Echo {
public static void main(String[] args) {
String line = IO.readln("Say something: ");
IO.println("You said: " + line);
}
}This is useful when you convert a compact file into a class. The calls to IO stay the same.
Summary of the design
IO is a small convenience, not a replacement for the I/O libraries. It handles one case well: print values and read lines at a terminal. Everything else is deliberately left to System.out, Scanner, BufferedReader, and java.io.Console.
Exercise
A program reads numbers with IO.readln() in a while (true) loop and adds them. It crashes with a NullPointerException when you pipe a file into it. What is wrong, and what is the fix?
Show answer
When the piped file ends, IO.readln() returns null, and the program calls a method such as trim() on it. The loop must stop on null, for example while ((line = IO.readln()) != null) { ... }.
Exercise
What does this compact source file print when the user types 5 at the prompt, and how do you change it to print 6?
void main() {
String s = IO.readln("n: ");
IO.println(s + 1);
}
Show answer
It prints 51, because s is a String and + concatenates. Convert first: IO.println(Integer.parseInt(s.trim()) + 1); prints 6.
Exercise
Why does IO.println("Total: %d", 7) fail to compile, and what is a correct replacement?
Show answer
IO.println accepts a single Object argument, so it has no format-string overload. Use IO.println("Total: %d".formatted(7)); or IO.println(String.format("Total: %d", 7));.