Sub topic 9
Reading with java.io.IO (Java 25)
This chapter assumes you can compile and run Java from the command line and use String, int, and try/catch. It also assumes you have read the earlier chapters on Scanner and the leftover newline pitfall. You need JDK 25 or later to run the examples.
What java.io.IO is
java.io.IO is a small class added in Java 25. It has static methods for the most common console tasks: print text, print a line, and read a line. It exists so that a first program does not need Scanner, System.in, or System.out.
| Method | What it does |
|---|---|
| `IO.print(Object obj)` | Prints the text form of `obj` without a line terminator |
| `IO.println(Object obj)` | Prints the text form of `obj`, then a line terminator |
| `IO.println()` | Prints only a line terminator |
| `IO.readln()` | Reads one line and returns it as a `String` |
| `IO.readln(String prompt)` | Prints `prompt`, then reads one line |
There is no IO.readInt() and no IO.readDouble(). readln always returns a String, and you convert it yourself. This differs from Scanner, which has nextInt and nextDouble.
Your first program
The spine example runs as a compact source file, which is a .java file with no class declaration. Save it as Greeter.java:
void main() {
String name = IO.readln("Name: ");
int age = Integer.parseInt(IO.readln("Age: ").trim());
IO.println(name + " is " + age);
}Run it with the source launcher, which compiles and runs in one step:
java Greeter.javaThree things to notice:
mainhas nopublic, nostatic, and noString[] args. Compact source files allow this.IOneeds no import in a compact source file. In a regular class you must writeimport java.io.IO;.- The prompt is printed exactly as given.
readln("Name: ")showsName:with the cursor right after it, so include the trailing space yourself.
Here is the same program as a regular class. The only changes are the import and the main declaration:
import java.io.IO;
public class Greeter {
public static void main(String[] args) {
String name = IO.readln("Name: ");
int age = Integer.parseInt(IO.readln("Age: ").trim());
IO.println(name + " is " + age);
}
}Why there is no leftover newline problem
In the earlier chapter you saw that nextInt reads a token and leaves the line terminator unread. A following nextLine then returns an empty string. IO.readln cannot do this, because every call reads a whole line and consumes its terminator. The text you get back has no terminator.
Each call consumes exactly one line, so you can mix numeric and text input freely:
void main() {
int count = Integer.parseInt(IO.readln("Count: ").trim());
String title = IO.readln("Title: ");
IO.println(count + " x " + title);
}The cost is that you now do the conversion and the error handling. The next sections cover both.
Converting text to numbers
Integer.parseInt accepts an optional leading + or - sign and the digits 0 to 9. It does not accept spaces, so " 42" and "42 " both throw NumberFormatException. That is why the examples call trim() first.
| Input line | `Integer.parseInt(line)` | `Integer.parseInt(line.trim())` |
|---|---|---|
| `42` | 42 | 42 |
| `42 ` (trailing space) | `NumberFormatException` | 42 |
| `` (empty) | `NumberFormatException` | `NumberFormatException` |
| `4 2` | `NumberFormatException` | `NumberFormatException` |
| `3.5` | `NumberFormatException` | `NumberFormatException` |
Use Double.parseDouble for decimals. It accepts surrounding whitespace on its own, but calling trim() anyway keeps your code consistent.
parseInt throws NumberFormatException for text that is not an integer. That exception is a subclass of IllegalArgumentException. It is not the InputMismatchException that Scanner.nextInt throws, so catch the right one.
A reusable validating reader
With Scanner you used hasNextInt to test before reading. With IO.readln you read first and then try to convert. This helper repeats the prompt until the user types an integer:
int readInt(String prompt) {
while (true) {
String line = IO.readln(prompt);
if (line == null) {
throw new IllegalStateException("Input ended");
}
try {
return Integer.parseInt(line.trim());
} catch (NumberFormatException e) {
IO.println("Not a number: " + line);
}
}
}
void main() {
int age = readInt("Age: ");
IO.println("Next year you will be " + (age + 1));
}The null check matters. readln returns null when the input has ended, for example when the user presses Ctrl+D on Linux or macOS, or Ctrl+Z then Enter on Windows. Without the check, line.trim() would throw a NullPointerException, which hides the real cause. The behavior matches Console.readLine, which is what readln is built on, so treat null as the normal end-of-input signal.
Reading until the input ends
Because readln returns null at the end, a loop can run until that happens. This program adds up numbers, one per line, and stops at the end of input or at a blank line. It reports lines it cannot parse and keeps going:
void main() {
int total = 0;
String line;
while ((line = IO.readln("Number (blank to stop): ")) != null && !line.isBlank()) {
try {
total += Integer.parseInt(line.trim());
} catch (NumberFormatException e) {
IO.println("Not a number: " + line);
}
}
IO.println("Total: " + total);
}Compare this with the hasNextInt loop from the Scanner chapter. That loop stopped at the first non-integer token. This one treats each line separately, so one bad line does not end the run. The trade-off is that you get lines, not tokens. A line like 1 2 3 is one bad line here, while Scanner would read three integers.
You can test it without typing by piping input:
printf '10\n20\nabc\n5\n' | java SumLines.javaThe program prints a prompt for each line, reports Not a number: abc, and ends with Total: 35, because readln returns null after the last line.
Errors and edge cases
- Unreadable input. If the underlying console fails with an I/O problem,
readlnthrowsjava.io.IOError. This is an uncheckedError, so you do not needthrowson your methods. This is a difference fromBufferedReader.readLine, which throws the checkedIOException. - Empty lines. An empty line returns
"", notnull. Only the end of input returnsnull. - Prompt text. The prompt is not a format string. If it contains
%, the character is printed as is. Build formatted prompts withString.formatorformattedfirst. - Printing.
IO.printlntakes anObject, soIO.println(42)andIO.println(name + " is " + age)both work. Passingnullprints the textnull. - Mixing with other readers. Do not mix
IO.readlnwith aScannerorBufferedReaderonSystem.inin the same program. AScannerbuffers input in advance, so lines it has already read are invisible toreadln, and the reverse can also lose lines. Pick one reader per program.
When to choose IO
| Situation | Good choice |
|---|---|
| Learning Java, short scripts, one-file programs run with `java File.java` | `IO.readln` |
| Several values on one line, or tokens split by a custom delimiter | `Scanner` |
| Password entry with no echo | `Console.readPassword` |
| Large input where speed matters | `BufferedReader` |
IO also works inside larger programs, as long as the JDK is version 25 or later. If your code must run on older JDKs, avoid it, because java.io.IO does not exist there and compilation fails with a "cannot find symbol" error.
Common mistakes
- Forgetting
import java.io.IO;in a regular class. Only compact source files add it for you. The compiler reports that it cannot find the symbolIO. - Parsing without
trim(). A stray trailing space makesparseIntthrow. - Catching
InputMismatchException. That exception belongs toScanner. WithreadlnandparseInt, catchNumberFormatException. - Ignoring
null. This works at the keyboard and fails on piped or redirected input. - Running with an older JDK. Check
java -version. The launcher on an older JDK reports thatjava.io.IOdoes not exist.
Exercise
Write a compact source file that asks for a width and a height with IO.readln, repeats each prompt until the user enters an integer, and prints the area. What must your code do if readln returns null, and why can you not use Scanner.hasNextInt for the retry check here?
Show answer
Reuse a helper such as readInt(String prompt) that loops: call IO.readln(prompt), throw an exception (for example IllegalStateException) if the result is null, then try Integer.parseInt(line.trim()) and print a message and loop again on NumberFormatException. Then main does int w = readInt("Width: "); int h = readInt("Height: "); IO.println("Area: " + (w * h)); The null check is needed because null means the input ended, and calling trim() on it would throw NullPointerException. hasNextInt belongs to Scanner, which reads tokens from its own buffer. readln returns a whole line as a String, so the only way to test it is to try the conversion and catch NumberFormatException.
Exercise
Why does mixing IO.readln for a count and IO.readln for a title work without an extra call, when mixing Scanner.nextInt and Scanner.nextLine does not?
Show answer
IO.readln always reads a complete line and consumes its line terminator, so the next call starts at the beginning of the next line. Scanner.nextInt reads only the number token and leaves the terminator in the input, so the following nextLine returns the empty rest of the first line.