The skipped question
Riya builds a canteen kiosk program. It asks for the number of cups, then the customer's name. But after she types 3 and presses Enter, the program doesn't wait for the name: it prints the bill with a blank name. She runs it again. Same thing.
Sir, my program skips the name question. I'm definitely calling nextLine()!
When you typed 3 and pressed Enter, two things went into the input buffer: the character 3 and an invisible newline. nextInt() took only the 3. The newline was still waiting, so nextLine() found a complete (empty) line straight away.
So it didn't skip the question; it answered it with nothing!
Exactly. Once you can see the buffer, Scanner stops being mysterious. Let's look inside.
What is Scanner?
java.util.Scanner is a class that breaks input into tokens separated by a delimiter (whitespace by default) and converts them into primitive values or Strings using methods such as nextInt(), nextDouble(), next() and nextLine(). To read from the keyboard, a Scanner is created on the standard input stream: new Scanner(System.in).
What you type goes into a waiting area called the input buffer. Scanner reads from it piece by piece: a number, a word or a whole line, whichever you ask for. Whatever it doesn't take stays in the buffer for the next read.
Words you'll meet in this lesson
Riya or 20 in Riya 20.\n (Windows sends \r\n).Scanner methods at a glance
| Method | Reads | Input Riya Sharma⏎ gives |
|---|---|---|
next() | One token (a word) | "Riya" |
nextLine() | The rest of the line, without the newline | "Riya Sharma" |
nextInt() | One token as an int | InputMismatchException (not a number) |
nextDouble(), nextLong(), nextBoolean() | One token as that type | Same rule as nextInt |
hasNextInt(), hasNext(), hasNextLine() | Checks without reading | false for hasNextInt |
Exam tip: Scanner is in java.util, so you must write import java.util.Scanner;. next() reads one word; nextLine() reads a whole line. After nextInt(), call an extra nextLine() to clear the leftover newline before reading a line.
Ways to read input in Java
Scanner
Easy and flexible: reads ints, doubles, words and lines, and can read from the keyboard, a String or a file. Slower for huge inputs.
Learning, small toolsBufferedReader
new BufferedReader(new InputStreamReader(System.in)). Reads whole lines fast; you parse numbers yourself with Integer.parseInt.
Command-line arguments
java Main Riya 20 → args[0], args[1]. No typing during the run; good for scripts and scheduled jobs.
Real applications
Web and mobile apps don't read the keyboard directly: input arrives as HTTP requests, form fields, files or messages, but parsing and validating it works the same way.
ProductionScanner can read from more than the keyboard
| Source | Create it with |
|---|---|
| Keyboard | new Scanner(System.in) |
| A String | new Scanner("10 20 30") |
| A file | new Scanner(Path.of("marks.txt")) (Module 13) |
Reading input, one step at a time
Import Scanner
Without this line javac reports “cannot find symbol: class Scanner”. The import only tells javac the full name; no code is copied.import java.util.Scanner;Create one Scanner on System.in
A Scanner object is created on the heap. It wraps the standard input stream and keeps its own buffer of characters that haven't been used yet.Scanner sc = new Scanner(System.in);Prompt, then read
UseSystem.out.print("Cups of chai: "); int cups = sc.nextInt();print(not println) so the cursor stays on the prompt line.nextInt()blocks: the program waits until a line is entered, then skips whitespace, reads digits and converts them to an int.Clear the newline before reading a line
sc.nextLine(); // throw away the leftover newline System.out.print("Name: "); String name = sc.nextLine();nextIntstops right after the digits. The newline stays in the buffer. The extranextLine()consumes it, so the next one waits for real input.Validate, and close when done
while (!sc.hasNextInt()) { System.out.print("Please enter a number: "); sc.next(); // discard the bad token } int age = sc.nextInt(); sc.close();hasNextInt()looks at the next token without removing it. Closing a Scanner on System.in also closes System.in itself, so do it only once, at the very end.
The input buffer: both views
Left: the console. Right: the characters waiting in Scanner's buffer, and what each method takes.
- The program creates a Scanner on System.in and waits for input.
- The user types Riya Sharma and presses Enter.
nextLine()returns the whole line, “Riya Sharma”, including the space.- For the cups question,
nextInt()returns 3. - The note question is “skipped”:
nextLine()returned an empty string immediately. - Typing three instead of 3 makes
nextInt()throw InputMismatchException.
- The buffer is empty, so the read blocks until the user presses Enter.
- The typed characters and an invisible
\narrive in the buffer. nextLine()consumes everything including the newline, and returns the text without it.nextInt()reads only the digits. The newline is left behind.- The next
nextLine()immediately finds that newline and returns "". - A non-numeric token makes
nextInt()throw. The token is not removed, so check withhasNextInt()first.
Reading input in real software
Production systems rarely read the keyboard, but they constantly read and validate input. The lessons from Scanner carry over directly.
Watch it with an example: the nextInt() then nextLine() trap
A kiosk asks for age, then name. The user types 21 Enter Riya Enter, but the name comes out empty. Watch Scanner's input buffer to see why.
- Typing: everything the user types goes into a buffer, including the Enter key (shown as ⏎).
- nextInt(): reads
2and1, makes the number 21, and stops. The ⏎ after it is still in the buffer. - nextLine(): reads characters until it finds a ⏎. The very first character is that leftover ⏎, so it returns an empty string.
- The bug: the program never waited for the name. This confuses almost every beginner (and appears in interviews).
- Fix: after
nextInt(), callsc.nextLine()once and ignore the result. It consumes the leftover ⏎. - Works: the next
nextLine()readsRiya. Another fix: read every line withnextLine()and convert withInteger.parseInt.
1. Command-line tools for developers and ops
Small internal tools (database migration helpers, admin utilities, installers) ask questions in the terminal and read answers just like a Scanner program.
2. Online coding tests and contests
Campus hiring tests and platforms like HackerRank feed test input through standard input. Reading it correctly, and fast enough, is the first step of every solution.
3. Validating form input
An age field, a PIN code or an amount typed into a web form arrives as text. The server checks it's a valid number in range before using it, the same idea as hasNextInt().
4. Parsing files line by line
Reading a CSV of student marks or a log file uses the same token/line ideas: read a line, split by a delimiter, convert each piece (Module 13).
5. Automated tests of console programs
Because System.in is just a stream of bytes, input can come from a file or a pipe instead of a person, which is how console programs are tested automatically.
Examples are simplified. Production systems use frameworks for input, but the parsing ideas are the same.
Riya's kiosk, fixed
In the live editor, type the input into the STDIN / input box before pressing Run. Each challenge's hint shows sample input.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Cups of chai: ");
int cups = sc.nextInt();
sc.nextLine(); // clear the leftover newline
System.out.print("Name: ");
String name = sc.nextLine();
System.out.print("Price per cup: ");
double price = sc.nextDouble();
System.out.println(name + ", your bill is Rs " + (cups * price));
sc.close();
}
}The console shows your typed input (3, Riya Sharma, 20) next to each prompt.
import java.util.Scanner;Scanner lives in thejava.utilpackage.new Scanner(System.in)One Scanner reading from the keyboard. Create it once and reuse it.System.out.print("…")printkeeps the cursor on the same line, so the answer appears next to the question.sc.nextLine();The fix for the trap: consumes the newline left bynextInt().sc.nextDouble()Reads a decimal number. Typing 20 is fine; it becomes 20.0.sc.close();Closes the Scanner and System.in. Do it once, at the end.
Watch the buffer drain
The input for this run is 3⏎Riya Sharma⏎20⏎. The note on each step shows what is left in Scanner's buffer.
Worked examples: real problems, solved and traced in memory
Real programs read input. Each program below reads from the keyboard with Scanner; the trace and the runner feed it the sample input shown. Watch each next…() call take the next piece of input and store it in a variable.
Read an item, quantity and price
Problem statement
A grocery counter types the item name, quantity and unit price. Print a bill line with the amount.
Basmati Rice 3 92.50
Basmati Rice x3 = Rs 277.5
Approach
nextLine()reads the whole first line (names can have spaces).nextInt()andnextDouble()read numbers.- Multiply and print.
Solution: run it live
What happens in memory, step by step
Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.
Average of three subjects
Problem statement
A teacher enters a student's name and three marks on one line. Print the total and the average with one decimal.
Ravi 78 85 91
Ravi: total 254, average 84.7
Approach
next()reads one word.- Three
nextInt()calls read the marks from the same line. printf("%.1f")shows one decimal.
Solution: run it live
What happens in memory, step by step
Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.
The nextInt + nextLine trap
Problem statement
A bank form reads an account number (a number) and then the holder's full name (a line). Read naively, the name comes out empty, because nextInt() leaves the Enter key in the input. Show the fix: an extra nextLine().
40021876 Asha Kumari Verma
Account: 40021876 Leftover was [] Holder: Asha Kumari Verma
Approach
nextInt()reads 40021876 but not the line break after it.- One
nextLine()consumes that leftover line break. - The next
nextLine()reads the real name.
Solution: run it live
What happens in memory, step by step
Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.
Check yourself
Quick revision
Lesson 2.6 in one screen
import java.util.Scanner;→Scanner sc = new Scanner(System.in);nextInt(),nextDouble(),next()read one token;nextLine()reads the rest of the line.- Typed input waits in a buffer; reads block until input arrives.
- The trap:
nextInt()leaves\n; callsc.nextLine()once before reading a line. - Bad input →
InputMismatchException; validate withhasNextInt(). - Use one Scanner; close it once at the end (it closes System.in).
- For huge inputs,
BufferedReader+Integer.parseIntis faster.
Interview and viva questions
What is the difference between next() and nextLine()?
next() skips leading whitespace and returns the next token, stopping at whitespace. nextLine() returns everything up to the end of the current line (which may be empty) and consumes the line terminator.
Why does nextLine() get skipped after nextInt()?
nextInt() reads only the number and leaves the newline in the buffer. The following nextLine() reads the remainder of that line, which is empty. Fix it by calling an extra nextLine() after nextInt(), or by reading every line with nextLine() and parsing it yourself.
Scanner vs BufferedReader?
Scanner is convenient: it parses ints, doubles and tokens, and works with many sources. BufferedReader is faster because it reads large blocks and only returns lines, leaving parsing to you. BufferedReader's readLine also throws IOException, which must be handled.
Is Scanner thread-safe?
No. A Scanner should be used by one thread at a time. Console input in multi-threaded programs is usually read by a single thread.
What is System.in?
A static field of the System class: an InputStream connected to the program's standard input, which is the keyboard by default but can be redirected from a file or another program.
Practice problems
Read input with Scanner and compute something with it. Each problem's sample input is used when you run it. The last three are business tasks.
Greet by name
Read a name and print "Hello, NAME!".
Meena
Hello, Meena!
Show solution and explanation
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
System.out.println("Hello, " + name + "!");
}
}How it works: nextLine reads the whole line typed.
Sum of two numbers
Read two integers and print their sum.
25 17
42
Show solution and explanation
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt(), b = sc.nextInt();
System.out.println(a + b);
}
}How it works: nextInt skips spaces and reads one number at a time.
Square of a decimal
Read a decimal number and print its square.
2.5
6.25
Show solution and explanation
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double x = sc.nextDouble();
System.out.println(x * x);
}
}How it works: nextDouble reads numbers with decimals.
Rectangle from input
Read length and width, print area and perimeter.
12 7
Area 84, perimeter 38
Show solution and explanation
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int l = sc.nextInt(), w = sc.nextInt();
System.out.println("Area " + l * w + ", perimeter " + 2 * (l + w));
}
}How it works: read once, use many times.
Number then sentence
Read a roll number, then a full name on the next line, and print both.
17 Kiran Rao
17: Kiran Rao
Show solution and explanation
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int roll = sc.nextInt();
sc.nextLine();
String name = sc.nextLine();
System.out.println(roll + ": " + name);
}
}How it works: the extra nextLine() eats the line break left by nextInt.
Bill with GST from input
Read an amount and print the GST (18%) and total.
1250
GST: Rs 225.0, total: Rs 1475.0
Show solution and explanation
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double amount = sc.nextDouble();
double gst = amount * 0.18;
System.out.println("GST: Rs " + gst + ", total: Rs " + (amount + gst));
}
}How it works: the same program now works for any amount typed in.
Fuel bill
Read litres and price per litre; print the bill rounded to the rupee.
23.5 104.7
Pay Rs 2460
Show solution and explanation
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double litres = sc.nextDouble(), rate = sc.nextDouble();
System.out.println("Pay Rs " + Math.round(litres * rate));
}
}How it works: 23.5 × 104.7 = 2460.45, rounded to 2460.
Customer details card
Read a customer's name (line), age and city, then print a one-line card.
Asha Verma 29 Pune
Asha Verma (29), Pune
Show solution and explanation
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
int age = sc.nextInt();
String city = sc.next();
System.out.println(name + " (" + age + "), " + city);
}
}How it works: nextLine for the full name first avoids the leftover-line-break problem.
Real-world scenario questions (asked in company interviews)
Input handling is where programs meet the messy real world. Decide your answer first, then open the model answer.
Correct answer, but “Time Limit Exceeded”
In an online test, your solution passes small test cases but fails the big ones with Time Limit Exceeded. The big input has 10 lakh numbers. Your algorithm is O(n). You read input with Scanner.nextInt() in a loop. What would you try first?
The interviewer is checking: do you know that input reading itself can be the bottleneck, and what the faster alternatives are?
Show a strong answer
With an O(n) algorithm, input reading is the likely bottleneck. Scanner parses every token with regular expressions, which is slow for millions of tokens.
- Switch to
BufferedReader: read lines, split them (or useStringTokenizer) and convert withInteger.parseInt. - For very large inputs, use a
DataInputStream-based fast reader orStreamTokenizer. - Also batch output: build it in a
StringBuilderand print once, rather than callingprintlnlakhs of times.
Avoid: rewriting the algorithm first without checking where the time is going.
NoSuchElementException on the second menu
A console admin tool has two methods, readUserDetails() and readPermissions(). Each creates its own Scanner(System.in) and closes it at the end, “to be tidy”. The first works; the second immediately throws NoSuchElementException: No line found. Why?
The interviewer is checking: do you understand that closing a Scanner closes the stream it wraps?
Show a strong answer
Closing the first Scanner also closed System.in. The second Scanner wraps a closed stream, so there's nothing left to read.
- Create one Scanner for System.in (for example in main) and pass it to the methods that need it.
- Close it once, when the program finishes (or not at all for System.in in small tools).
- Tidiness rule: close resources you opened, like files. System.in was opened by the JVM.
Avoid: catching the exception and creating yet another Scanner.
The program crashes when a user types a letter
During a demo of a training ATM simulator, a tester typed “5oo” instead of 500 for the withdrawal amount and the program crashed with a stack trace. The client was not impressed. How would you make input handling robust?
The interviewer is checking: do you validate input instead of assuming users type correctly?
Show a strong answer
- Never call
nextInt()blindly. Check withhasNextInt()and discard bad tokens withnext(), or read the whole line and parse it inside a try-catch forNumberFormatException. - Validate the range and rules too: positive, a multiple of 100, within the daily limit.
- Show a clear message and ask again, instead of exiting.
- Add tests with empty input, letters, negative numbers and huge numbers.
Avoid saying: “Users should type correctly.” Assume every input can be wrong.
Works on your laptop, fails on the European server
A small import job reads prices like 19.5 from a file with scanner.nextDouble(). It runs fine in India, but on a server configured with a German locale, it throws InputMismatchException on every price. What's going on?
The interviewer is checking: do you know that Scanner's number parsing depends on the default locale?
Show a strong answer
Scanner uses the machine's default locale to parse numbers. In a German locale, the decimal separator is a comma (19,5), so 19.5 isn't recognised as a number.
- For machine-generated data, fix the locale explicitly:
scanner.useLocale(Locale.ROOT), or read the text and useDouble.parseDouble, which always expects a dot. - Keep user-facing formatting (display) locale-aware, but parsing of data files locale-independent.
- Add a test that runs with a different default locale.
Avoid: “Change the server's locale.” The code should not depend on it.