Java Console Input and Output: Scanner, Console and printf Formatting
Read keyboard input with Scanner (nextLine, next, nextInt, hasNextInt) and avoid the nextInt/nextLine trap, read passwords with Console, and format output precisely with printf, String.format and formatted: conversions, flags, width, precision, argument indexes and locales.
kvi5hnuCode Sprout team member11 min readOn this page
So far, our programs have only printed fixed results. Real programs interact: they ask questions, read answers and present results neatly. Modern applications use graphical or web interfaces, but those need many more tools. While you're learning the language, the console (terminal) is the simplest place to do input and output.
This article covers:
- reading input with
Scanner, and its most common pitfall, - reading passwords with
Console, - formatting output with
printf,String.formatandformatted.
Reading Input with Scanner
Printing to the standard output stream is easy: System.out.println. Reading from the standard input stream, System.in, takes one more step. System.in only delivers raw bytes, so you wrap it in a Scanner, which turns those bytes into words, numbers and lines:
import java.util.Scanner;
public class InputTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("What is your name? ");
String name = in.nextLine();
System.out.print("How old are you? ");
int age = in.nextInt();
System.out.println("Hello, " + name + ". Next year, you'll be " + (age + 1) + ".");
}
}
A sample run (user input in the terminal after each prompt):
What is your name? Ada Lovelace
How old are you? 36
Hello, Ada Lovelace. Next year, you'll be 37.
Notes on this program:
import java.util.Scanner;Scannerlives in thejava.utilpackage. Only classes injava.lang(likeString,System,Math) are available without an import. You'll often seeimport java.util.*;, which imports every class in the package. Packages and imports have their own article in the objects and classes part.new Scanner(System.in)creates aScannerobject. Thenewoperator and constructors are explained in the objects and classes part.print, notprintln, for prompts: the cursor stays on the same line, so the user types right after the question.
Scanner methods
| Method | Reads | Example input → result |
|---|---|---|
String nextLine() | the rest of the current line (without the line break) | Ada Lovelace⏎ → "Ada Lovelace" |
String next() | the next word (token), delimited by whitespace | Ada Lovelace → "Ada" |
int nextInt() | the next token as an int | 36 → 36 |
double nextDouble() | the next token as a double | 1.75 → 1.75 |
long nextLong(), boolean nextBoolean(), … | other types | |
boolean hasNext() | is there another token? | |
boolean hasNextInt(), hasNextDouble() | is the next token a valid int / double? | |
boolean hasNextLine() | is there another line? |
Use nextLine when the input may contain spaces (full names, sentences), and next/nextInt/nextDouble for single words and numbers.
import java.util.InputMismatchException;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner("Ada Lovelace\n36 1.75\nyes no\n");
String name = in.nextLine();
int age = in.nextInt();
double height = in.nextDouble();
String word = in.next();
System.out.println(name + "|" + age + "|" + height + "|" + word);
System.out.println(in.hasNextInt() + " " + in.next() + " " + in.hasNext());
Scanner numbers = new Scanner("3 4 x 5");
int total = 0;
while (numbers.hasNext()) {
if (numbers.hasNextInt()) {
total += numbers.nextInt();
} else {
System.out.println("skipping " + numbers.next());
}
}
System.out.println("total = " + total);
try {
new Scanner("abc").nextInt();
} catch (InputMismatchException e) {
System.out.println("InputMismatchException");
}
}
}
Ada Lovelace|36|1.75|yes
false no false
skipping x
total = 12
InputMismatchException
If the next token isn't a valid number, nextInt throws an InputMismatchException (and leaves the bad token unread). Use hasNextInt() to check first, as the loop above does, so the program doesn't crash on a typo. (The try/catch construct is covered in the exceptions part.)
The nextInt + nextLine trap
This is the most common beginner bug with Scanner. nextInt, nextDouble and next read a token and stop before the line break that follows it. A subsequent nextLine then reads only that leftover line break and returns an empty string:

import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner("42\nAda\n");
int number = in.nextInt();
String leftover = in.nextLine();
String name = in.nextLine();
System.out.println(number + " [" + leftover + "] [" + name + "]");
Scanner better = new Scanner("42\nAda\n");
int n = Integer.parseInt(better.nextLine().strip());
String nm = better.nextLine();
System.out.println(n + " [" + nm + "]");
}
}
42 [] [Ada]
42 [Ada]
Two fixes:
- After
nextInt()(ornextDouble()), callin.nextLine()once to discard the rest of the line. - Read every input with
nextLine()and convert it yourself:Integer.parseInt(line.strip())orDouble.parseDouble(...). This is usually the more robust approach for line-based interaction.
Reading Passwords with Console
Scanner shows everything the user types, which is a bad idea for passwords. The Console class can read input without echoing it:
import java.io.Console;
import java.util.Arrays;
Console cons = System.console();
if (cons == null) {
System.err.println("No console available");
return;
}
String username = cons.readLine("User name: ");
char[] password = cons.readPassword("Password: ");
// ... check the password ...
Arrays.fill(password, '*'); // wipe it as soon as you're done
System.console()returns the console, ornullif the program isn't connected to an interactive terminal (for example, when input is redirected from a file, or in some IDE consoles). Always check fornull. Since Java 22,cons.isTerminal()tells you whether it's attached to a real terminal.readPasswordreturns achar[], not aString. Strings are immutable and may stay in memory until garbage-collected; you can't erase them. An array can be overwritten right after use, which shortens the time the secret sits in memory.readLine(prompt, args…)andreadPassword(prompt, args…)acceptprintf-style format arguments in the prompt.Consolereads whole lines only; it has nonextIntornext. Combine it withInteger.parseIntwhen needed.
Formatting Output with printf
Printing a number with print or println shows all its significant digits:
double x = 10000.0 / 3.0;
System.out.println(x); // 3333.3333333333335
That's no good for prices or tables. printf ("print formatted"), which follows the conventions of C's printf, gives you control:
System.out.printf("%8.2f", x); // " 3333.33": width 8, 2 decimals
System.out.printf("Hello, %s. Next year, you'll be %d.%n", name, age + 1);
The first argument is the format string. Each format specifier, starting with %, is replaced by the next argument, formatted as described. The letter at the end, the conversion, says what kind of value it is: d for integers, f for floating-point, s for strings.

The full syntax is %[argument_index$][flags][width][.precision]conversion. Everything except % and the conversion is optional.
Conversions
| Conversion | Type | Example |
|---|---|---|
d | decimal integer | 42 |
x / X | hexadecimal integer | ff / FF |
o | octal integer | 10 (for 8) |
f / F | fixed-point floating-point | 3333.33 |
e / E | exponential floating-point | 3.333333e+03 |
g / G | general: the shorter of e and f | 3333.33 |
a / A | hexadecimal floating-point | 0x1.a0aaaaaaaaaabp11 |
s / S | string (any object, via toString) | Hello / HELLO |
c / C | character | J |
b / B | boolean | true / TRUE |
h / H | hash code in hex | d01 |
n | the platform's line separator (no argument) | |
% | a literal percent sign (no argument) | % |
t / T | legacy date/time formatting (prefer java.time formatters) |
Uppercase conversions produce uppercase output: %8.2E turns 3333.33 into 3.33E+03. Use %n for line breaks in format strings. It produces \r\n on Windows and \n elsewhere, matching the platform.
%s works with any object: it calls the object's toString method (or formatTo, if the class implements the Formattable interface). You'll write your own toString methods in the inheritance part.
Flags
| Flag | Effect | Example (%…f of 3333.33 or as noted) |
|---|---|---|
- | left-justify within the width | 3333.33 (%-10.2f, padding on the right) |
0 | pad with leading zeros | 003333.33 |
+ | always show the sign | +3333.33 |
| space | a space before positive numbers | 3333.33 |
, | group separators | 3,333.33 |
( | negative numbers in parentheses (accounting style) | (3333.33) |
# with f | always include a decimal point | 3333. |
# with x/o | add the 0x / 0 prefix | 0xcafe |
n$ | use argument number n (1-based) | %1$d %1$x → 159 9f |
< | reuse the previous argument | %d %<x → 159 9f |
Flags can be combined: "%,(.2f" uses group separators and parentheses for negatives.
Width is the minimum number of characters; output is padded with spaces (on the left, unless you use -). Longer values are never truncated. Precision means "digits after the decimal point" for f and e, and "maximum number of characters" for s.
import java.util.Locale;
public class Solution {
public static void main(String[] args) {
double x = 10000.0 / 3.0;
System.out.println(x);
System.out.printf("%8.2f|%n", x);
System.out.printf("%-10s|%5d|%05d|%x|%X|%o%n", "Ada", 42, 42, 255, 255, 8);
System.out.printf("%e|%.3E|%g%n", x, x, x);
System.out.printf(Locale.US, "%,.2f|%+d|% d|%(.2f|%#x|%#.0f%n", x * 1000, 5, 5, -x, 51966, x);
System.out.printf("%1$d %1$x %1$o | %d %<x%n", 159, 159);
System.out.printf("%s %S %c %b %B %%%n", "hi", "hi", 'J', null, true);
System.out.printf("%10.4s|%n", "Javascript");
System.out.printf("%.2f %.0f %.0f%n", 2.675, 2.5, 3.5);
System.out.printf(Locale.GERMANY, "%,.2f%n", x * 1000);
String message = String.format("Hello, %s. Next year, you'll be %d.", "Ada", 37);
System.out.println(message);
System.out.println("%s scored %d%%".formatted("Linus", 85));
}
}
3333.3333333333335
3333.33|
Ada | 42|00042|ff|FF|10
3.333333e+03|3.333E+03|3333.33
3,333,333.33|+5| 5|(3333.33)|0xcafe|3333.
159 9f 237 | 159 9f
hi HI J false TRUE %
Java|
2.68 3 4
3.333.333,33
Hello, Ada. Next year, you'll be 37.
Linus scored 85%
Things to notice:
%bprintsfalsefornullandtruefor any other non-boolean value. It's really meant for booleans.%10.4skeeps the first 4 characters (Java) and pads them to width 10.%.0frounds half up (2.5 → 3, 3.5 → 4), which differs fromMath.rint's "round half to even".%.2fof 2.675 gives 2.68 because the formatter rounds the shortest decimal representation of thedouble,2.675.- A specifier whose argument has the wrong type, such as
%dwith adouble, throws anIllegalFormatConversionExceptionat runtime. A missing argument throws aMissingFormatArgumentException. IntelliJ IDEA flags such mismatches as you type.
Formatting without printing: String.format and formatted
To create a formatted string instead of printing it, use the static method String.format, or (Java 15+) the instance method formatted on the format string itself:
String message = String.format("Hello, %s. Next year, you'll be %d.", name, age + 1);
String message2 = "Hello, %s. Next year, you'll be %d.".formatted(name, age + 1);
Both produce the same result. formatted reads nicely at the end of a text block.
Locales
Formatting follows the user's locale. On a computer with German settings, printf("%,.2f", 3333333.33) prints 3.333.333,33: the period groups digits and the comma marks decimals. That's right for messages shown to people, but wrong for files that programs will read back (CSV, JSON, configuration files). For those, pass an explicit locale as the first argument:
System.out.printf(Locale.US, "%.2f%n", x); // always uses '.' for decimals
String csv = String.format(Locale.ROOT, "%.2f", x);
Locale is in java.util. The examples in this course pass Locale.US whenever the exact output depends on separators.
Common questions
Why does System.console() return null in my IDE?
The program isn't attached to an interactive terminal, so there is no console. This also happens when input or output is redirected. On JDK 25 the method returns null in those cases. Fall back to a Scanner on System.in, or run the program from a real terminal when you need hidden password input.
Should I close a Scanner on System.in?
In a small program it doesn't matter. Be careful in larger ones, though: closing the Scanner also closes System.in, and nothing can read from standard input after that. Create one Scanner for System.in and keep it for the whole program, or don't close it. Always close scanners that read files, preferably with try-with-resources.
How do I read all lines until the input ends?
Use while (in.hasNextLine()) { String line = in.nextLine(); ... }. When input comes from a file or pipe, the loop ends at end-of-file. In a terminal, the user ends input with Ctrl+D (macOS/Linux) or Ctrl+Z then Enter (Windows). For large inputs, BufferedReader.readLine() is much faster than Scanner.
Why do my printf numbers use commas instead of periods?
printf uses your computer's default locale, so a German or French machine uses a comma as the decimal separator. Pass Locale.US or Locale.ROOT as the first argument when the output is read by programs, and leave it out for messages shown to people.
How does %.2f round?
It uses HALF_UP on the shortest decimal representation of the double, so 2.675 becomes 2.68 and 0.25 with %.1f becomes 0.3. For exact control, such as banker's rounding for money, round a BigDecimal with setScale and an explicit RoundingMode first.
Summary
- Wrap
System.inin aScanner(import java.util.Scanner) and read withnextLine,next,nextIntandnextDouble; test withhasNext,hasNextIntandhasNextLine. nextInt/nextleave the line break unread. A followingnextLine()returns"". Consume it, or read lines and parse them withInteger.parseInt.- Bad numeric input throws
InputMismatchException; check withhasNextIntfirst. Console(System.console(), which may benull) reads passwords without echo into achar[]that you should wipe after use.printfformat specifiers:%[index$][flags][width][.precision]conversion, with conversions such asd x o f e g s c b n %and flags such as- 0 + , ( # $ <. Use%nfor line breaks.String.format(...)and"...".formatted(...)build formatted strings without printing.- Formatting is locale-sensitive: pass
Locale.USorLocale.ROOTfor machine-readable output.
Practice Questions
What does System.out.printf("[%6.1f][%-6d][%06d]%n", 3.14159, 42, 42); print?
[ 3.1][42 ][000042]: width 6 with one decimal (right-aligned), left-justified integer in width 6, zero-padded integer in width 6.
A program reads an age with nextInt() and then the city with nextLine(), but city is always empty. Why, and how do you fix it?
nextInt() stops before the line break after the number, so nextLine() returns the empty remainder of that line. Call in.nextLine() once after nextInt() to discard it, or read the age with Integer.parseInt(in.nextLine().strip()).
Why does Console.readPassword return char[] rather than String?
A String is immutable and can't be erased; it stays in memory until garbage-collected (and may appear in memory dumps). A char[] can be overwritten (Arrays.fill(pw, '*')) right after use.
How would you print the int value 255 as both decimal and hex using a single argument?
System.out.printf("%d %<x%n", 255); or System.out.printf("%1$d %1$x%n", 255);. Both print 255 ff.
A program writes prices to a CSV file with String.format("%.2f", price). A colleague in France gets "19,99", which breaks the CSV. What's the fix?
Formatting uses the default locale, and French uses a comma as the decimal separator. Use a fixed locale for machine-readable output: String.format(Locale.ROOT, "%.2f", price) (or Locale.US).
Write a format string that prints a table row: a name left-aligned in 12 characters, then a score right-aligned in 5 characters, then a percentage with one decimal and a % sign.
"%-12s%5d%6.1f%%%n". For example, printf("%-12s%5d%6.1f%%%n", "Ada", 92, 92.0) prints Ada 92 92.0%.
Previous: The Java String API, Code Points, StringBuilder and Text Blocks
Next: Java File Input and Output Basics: Reading and Writing Text Files
Related reading
- The Java String API, Code Points, StringBuilder and Text Blocks
- Java Strings: Concatenation, Substrings, Immutability and Comparing with equals
- Java Switch Expressions: Arrow Labels, Multiple Labels, yield and case null
- Java Operators: Increment, Relational, Logical, Conditional, Bitwise and Precedence
- Java Type Conversion and Casting: Widening, Narrowing and Compound Assignment

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.