IO.readln()
Prints a prompt and reads a line typed by the user.
Available since: Java 25
Syntax
static String readln(String prompt)Parameters
| Parameter | Type | Description |
|---|---|---|
| prompt | String | The text shown before input. Can be called without an argument. |
Return value
StringThe entered line without the line break, or null if the input has ended.
Examples
Reading a name. In the console (the user typed Anna):
void main() {
String name = IO.readln("What is your name? ");
IO.println("Hello, " + name + "!");
}Output:
What is your name? Anna
Hello, Anna!Reading a number — the string must be parsed (the user typed 7):
void main() {
int n = Integer.parseInt(IO.readln("Number: "));
IO.println(n + " squared is " + n * n);
}Output:
Number: 7
7 squared is 49Notes
readln() always returns a string. Numbers are parsed with Integer.parseInt() or Double.parseDouble(); on invalid input they throw NumberFormatException. If the input is closed (for example, the file has ended), the method returns null.
To read many numbers in a row on one line, Scanner is handier.
See also
- IO.println() — Prints a value to the console and ends the line.
- IO.print() — Prints a value to the console without ending the line.
- Scanner — Reads input piece by piece: whole lines (nextLine) or separate words and numbers.
- Integer.parseInt() — Converts a string containing an integer to an int.
Related recipes
In the tutorial
- Keyboard input — How to read user input in Java: IO.readln, turning input into a number and the Scanner class.