Practice Questions — Taking Input with Scanner
← Back to NotesTopic-Specific Questions
Question 1
Easy
What is the output if the user enters 10?
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
System.out.println(x * 2);nextInt() reads 10. Then we print 10 * 2.
20Question 2
Easy
What is the output if the user enters "Ravi"?
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
System.out.println("Hello " + name);nextLine() reads the entire line.
Hello RaviQuestion 3
Easy
What does
sc.next() return if the user types "Sita Ram" and presses Enter?next() reads only up to the first whitespace.
SitaQuestion 4
Easy
What is the output if the user enters 5 and 3?
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println(a + b);Both nextInt() calls read one integer each.
8Question 5
Easy
What is the output if the user enters 3.14?
Scanner sc = new Scanner(System.in);
double d = sc.nextDouble();
System.out.println(d + 1);nextDouble() reads a double value.
4.140000000000001 (or approximately 4.14)Question 6
Medium
What happens if the user enters 25 and then presses Enter? What will name contain?
Scanner sc = new Scanner(System.in);
int age = sc.nextInt();
String name = sc.nextLine();
System.out.println("Name: '" + name + "'");This is the classic nextLine() bug.
Name: '' (empty string)Question 7
Medium
What is the output if the user enters "true"?
Scanner sc = new Scanner(System.in);
boolean flag = sc.nextBoolean();
System.out.println(!flag);nextBoolean() reads true or false as a boolean.
falseQuestion 8
Medium
What is the output if the user enters "Hello World Java"?
Scanner sc = new Scanner(System.in);
String a = sc.next();
String b = sc.next();
String c = sc.next();
System.out.println(c + " " + b + " " + a);Each next() reads one word.
Java World HelloQuestion 9
Medium
What is the output if the user enters 10 and then 20 on the same line separated by a space?
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println("Sum: " + (a + b));nextInt() can read integers separated by whitespace on the same line.
Sum: 30Question 10
Medium
What exception is thrown if the user enters "abc" here?
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();"abc" cannot be parsed as an integer.
java.util.InputMismatchExceptionQuestion 11
Hard
What is the output if the user enters 5, then presses Enter, then types "Deepa"?
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
sc.nextLine(); // consume newline
String s1 = sc.nextLine();
String s2 = sc.nextLine();
System.out.println(s1);
System.out.println(s2);After consuming the newline, s1 reads the next line. But what about s2?
The program reads 5, consumes the newline, reads "Deepa" into s1, then waits for more input for s2.
Question 12
Hard
What is the output?
Scanner sc = new Scanner(System.in);
// User types: 10 20 30
int a = sc.nextInt();
String rest = sc.nextLine();
System.out.println("a = " + a);
System.out.println("rest = '" + rest + "'");nextInt() reads the first token. nextLine() reads the remaining part of the line.
a = 10rest = ' 20 30'Question 13
Medium
Why does the nextLine() bug occur after nextInt()? Explain the internal mechanism.
Think about what character is left in the input buffer after the user presses Enter.
When the user types a number and presses Enter, the input stream contains the digits followed by a newline character (\n).
nextInt() reads and consumes only the digits, leaving the \n in the buffer. The subsequent nextLine() sees the \n and immediately returns an empty string, because nextLine() reads up to (and including) the next newline character.Question 14
Medium
What is the difference between
next() and nextLine()?Think about whitespace handling.
next() reads a single token (a word) delimited by whitespace. It skips leading whitespace and stops at the first whitespace character after the token. nextLine() reads the entire remaining line up to the newline character, including spaces within the line.Question 15
Hard
When should you use BufferedReader instead of Scanner? What are the trade-offs?
Think about speed vs convenience.
Use BufferedReader when reading large amounts of input (competitive programming, file processing) because it is significantly faster than Scanner. Scanner is convenient because it parses types directly (
nextInt(), nextDouble()), but this convenience comes with a performance cost. BufferedReader reads raw strings, requiring manual parsing with Integer.parseInt() etc. BufferedReader also throws checked IOException, which you must handle.Question 16
Easy
What is the output if the user enters "true"?
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
System.out.println(s.length());nextLine() reads the string 'true', which has 4 characters.
4Question 17
Medium
What is the output if the user enters " hello "?
Scanner sc = new Scanner(System.in);
String s = sc.next();
System.out.println("'" + s + "'");next() skips leading whitespace and reads the first token.
'hello'Question 18
Hard
What is the output if the user enters 5 on line 1, then "Hello World" on line 2?
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
String s = sc.nextLine();
System.out.println(n + ": " + s);Using Integer.parseInt(sc.nextLine()) avoids the nextLine bug entirely.
5: Hello WorldMixed & Application Questions
Question 1
Easy
Write a program that reads two integers from the user and prints their sum, difference, product, and quotient.
Use nextInt() twice. Be careful with integer division.
import java.util.Scanner;
public class BasicCalc {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first number: ");
int a = sc.nextInt();
System.out.print("Enter second number: ");
int b = sc.nextInt();
System.out.println("Sum: " + (a + b));
System.out.println("Difference: " + (a - b));
System.out.println("Product: " + (a * b));
if (b != 0) {
System.out.println("Quotient: " + (a / b));
} else {
System.out.println("Cannot divide by zero");
}
sc.close();
}
}Question 2
Easy
What is the output if the user enters 7?
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println(n + " squared is " + n * n);Compute 7 * 7.
7 squared is 49Question 3
Medium
What is the output if the user types "42abc"?
Scanner sc = new Scanner(System.in);
if (sc.hasNextInt()) {
System.out.println("Int: " + sc.nextInt());
} else {
System.out.println("Not an int: " + sc.next());
}Is "42abc" a valid integer token?
Not an int: 42abcQuestion 4
Medium
Write a program that reads a student's name (may contain spaces), roll number (int), and CGPA (double) and prints them in a formatted manner. Handle the nextLine bug correctly.
Read roll number first, consume the newline, then read name.
import java.util.Scanner;
public class StudentInfo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter roll number: ");
int roll = sc.nextInt();
System.out.print("Enter CGPA: ");
double cgpa = sc.nextDouble();
sc.nextLine(); // Consume leftover newline
System.out.print("Enter full name: ");
String name = sc.nextLine();
System.out.println("\n--- Student Details ---");
System.out.println("Name: " + name);
System.out.println("Roll: " + roll);
System.out.println("CGPA: " + cgpa);
sc.close();
}
}Question 5
Medium
What is the output if the user enters "Java Programming"?
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
System.out.println("Length: " + s.length());
System.out.println("First char: " + s.charAt(0));Count all characters including the space.
Length: 16First char: JQuestion 6
Hard
What is the output if the user enters "3 7"?
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
String[] parts = line.split(" ");
int a = Integer.parseInt(parts[0]);
int b = Integer.parseInt(parts[1]);
System.out.println("Max: " + Math.max(a, b));The line is split into two parts, then each is parsed.
Max: 7Question 7
Hard
What is the output if the user enters 5, then 10?
Scanner sc = new Scanner(System.in);
int x = Integer.parseInt(sc.nextLine());
int y = Integer.parseInt(sc.nextLine());
System.out.println(x + y);
System.out.println("" + x + y);In the second println, the empty string causes string concatenation, not addition.
15510Question 8
Hard
What happens with this code?
Scanner sc = new Scanner(System.in);
// User types: 3.14
int num = sc.nextInt();Can nextInt() read a decimal number?
InputMismatchException is thrown at runtime.Question 9
Hard
Write a program using BufferedReader that reads N (an integer), then reads N names (each on a separate line), and prints them in reverse order.
Use a String array to store the names. Read N with Integer.parseInt(br.readLine()).
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class ReverseNames {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine().trim());
String[] names = new String[n];
for (int i = 0; i < n; i++) {
names[i] = br.readLine();
}
for (int i = n - 1; i >= 0; i--) {
System.out.println(names[i]);
}
br.close();
}
}Question 10
Easy
What is the output if the user enters 4 and 6?
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println("Product: " + a * b);Read two ints and multiply.
Product: 24Question 11
Medium
What is the output if the user enters "hello"?
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
System.out.println(s.toUpperCase());
System.out.println(s.charAt(0));toUpperCase returns a new string. charAt(0) returns the first character.
HELLOhQuestion 12
Hard
Write a program that reads integers from the user until they enter -1 (sentinel value). Print the sum and count of all entered numbers (excluding -1).
Use a while loop with nextInt(). Break when input is -1.
import java.util.Scanner;
public class SentinelInput {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int sum = 0, count = 0;
System.out.println("Enter numbers (-1 to stop):");
while (true) {
int n = sc.nextInt();
if (n == -1) break;
sum += n;
count++;
}
System.out.println("Count: " + count);
System.out.println("Sum: " + sum);
sc.close();
}
}Multiple Choice Questions
MCQ 1
Which package must be imported to use the Scanner class?
Answer: B
B is correct. The Scanner class is in the
B is correct. The Scanner class is in the
java.util package. java.lang is auto-imported. java.io contains I/O classes like BufferedReader. java.scanner does not exist.MCQ 2
Which method reads an entire line of input including spaces?
Answer: B
B is correct.
B is correct.
nextLine() reads the entire line up to the newline. next() reads only one token (word). nextWord() does not exist. readLine() is a BufferedReader method, not Scanner.MCQ 3
What argument is passed to the Scanner constructor for keyboard input?
Answer: B
B is correct.
B is correct.
System.in is the standard input stream (keyboard). System.out is the output stream. System.keyboard does not exist. System.console() exists but returns a Console object, not an InputStream.MCQ 4
Which method reads the next integer from input?
Answer: C
C is correct.
C is correct.
nextInt() is the Scanner method that reads the next token and parses it as an int. The other methods do not exist in the Scanner class.MCQ 5
What does next() return if the user types "Raj Kumar"?
Answer: B
B is correct.
B is correct.
next() reads one token delimited by whitespace. It returns "Raj" and leaves "Kumar" in the buffer.MCQ 6
What causes the nextLine() bug after nextInt()?
Answer: C
C is correct. When the user types a number and presses Enter,
C is correct. When the user types a number and presses Enter,
nextInt() reads the number but leaves the \n in the buffer. The subsequent nextLine() consumes that \n and returns an empty string.MCQ 7
How do you fix the nextLine() bug after nextInt()?
Answer: B
B is correct. Adding an extra
B is correct. Adding an extra
sc.nextLine() call after nextInt() consumes the leftover newline character. The other methods either do not exist (nextString()) or do not solve this problem.MCQ 8
What exception is thrown when nextInt() receives non-integer input?
Answer: B
B is correct. Scanner throws
B is correct. Scanner throws
InputMismatchException when the next token does not match the expected type. NumberFormatException is thrown by Integer.parseInt() and similar parsing methods, not by Scanner directly.MCQ 9
What does hasNextInt() do?
Answer: C
C is correct.
C is correct.
hasNextInt() returns true if the next token can be interpreted as an int, and false otherwise. It does not consume the token from the input buffer, making it useful for validation before calling nextInt().MCQ 10
Which of these is the fastest way to read input in Java?
Answer: C
C is correct.
C is correct.
BufferedReader is significantly faster than Scanner because it reads raw bytes in bulk without regex-based token parsing. For competitive programming and large inputs, BufferedReader is the preferred choice.MCQ 11
What happens when you close a Scanner that wraps System.in?
Answer: B
B is correct. Closing the Scanner also closes the underlying
B is correct. Closing the Scanner also closes the underlying
System.in stream. After that, no new Scanner can read from System.in. This is why you should use only one Scanner for System.in throughout your program.MCQ 12
What is the correct way to use try-with-resources with Scanner?
Answer: B
B is correct. The try-with-resources syntax declares the resource inside parentheses after
B is correct. The try-with-resources syntax declares the resource inside parentheses after
try. The resource must implement AutoCloseable. Option D uses C# syntax. Option A is a regular try block that does not auto-close the resource.MCQ 13
Which method should you use to read a line with BufferedReader?
Answer: B
B is correct.
B is correct.
readLine() is the BufferedReader method that reads one line of text. nextLine() is a Scanner method. The other options do not exist in BufferedReader.MCQ 14
What exception does Integer.parseInt("abc") throw?
Answer: B
B is correct.
B is correct.
Integer.parseInt() throws NumberFormatException when the string cannot be parsed as an integer. This is different from Scanner, which throws InputMismatchException. Knowing this distinction matters in placement exams.MCQ 15
What is the output of the following code if the user types "5 10 15" on a single line?
Scanner sc = new Scanner(System.in);
int sum = 0;
while (sc.hasNextInt()) { sum += sc.nextInt(); }
System.out.println(sum);Answer: C
C is correct.
C is correct.
hasNextInt() returns true three times (for 5, 10, 15). Each nextInt() reads and adds the value. Sum = 5 + 10 + 15 = 30. After all tokens are consumed, hasNextInt() waits for more input. In practice, the user would need to signal end-of-input (Ctrl+Z on Windows or Ctrl+D on Unix) for the loop to end.MCQ 16
What does sc.nextLine() return?
Answer: C
C is correct.
C is correct.
nextLine() reads and returns the entire line of input up to (but not including) the newline character.MCQ 17
Which of the following reads a double value from Scanner?
Answer: B
B is correct.
B is correct.
nextDouble() reads the next token as a double. nextFloat() reads a float (different precision). The other methods do not exist in Scanner.MCQ 18
What is the difference between InputMismatchException and NumberFormatException?
Answer: B
B is correct.
B is correct.
InputMismatchException is thrown by Scanner methods (nextInt, nextDouble, etc.) when the input does not match the expected type. NumberFormatException is thrown by parsing methods like Integer.parseInt() when the string cannot be converted to a number.Coding Challenges
Challenge 1: Temperature Converter
EasyWrite a program that reads a temperature in Celsius from the user and converts it to Fahrenheit using the formula: F = (C * 9/5) + 32. Print the result rounded to 2 decimal places.
Sample Input
Enter temperature in Celsius: 37.5
Sample Output
37.5 C = 99.50 F
Use Scanner with nextDouble(). Use printf or String.format for 2 decimal places.
import java.util.Scanner;
public class TempConverter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter temperature in Celsius: ");
double celsius = sc.nextDouble();
double fahrenheit = (celsius * 9.0 / 5.0) + 32;
System.out.printf("%.1f C = %.2f F%n", celsius, fahrenheit);
sc.close();
}
}Challenge 2: Student Report Card
EasyRead a student's name, roll number, and marks in 3 subjects. Print the total, average (2 decimal places), and whether the student passed (average >= 40) or failed.
Sample Input
Enter name: Sneha Gupta
Enter roll number: 42
Enter marks in 3 subjects: 78 85 92
Sample Output
Name: Sneha Gupta
Roll: 42
Total: 255
Average: 85.00
Result: Pass
Handle the nextLine bug correctly. Read all three marks on one line or separately.
import java.util.Scanner;
public class ReportCard {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter roll number: ");
int roll = sc.nextInt();
sc.nextLine();
System.out.print("Enter name: ");
String name = sc.nextLine();
System.out.print("Enter marks in 3 subjects: ");
int m1 = sc.nextInt();
int m2 = sc.nextInt();
int m3 = sc.nextInt();
int total = m1 + m2 + m3;
double avg = total / 3.0;
System.out.println("Name: " + name);
System.out.println("Roll: " + roll);
System.out.println("Total: " + total);
System.out.printf("Average: %.2f%n", avg);
System.out.println("Result: " + (avg >= 40 ? "Pass" : "Fail"));
sc.close();
}
}Challenge 3: Word Counter
MediumRead a sentence from the user and count the number of words in it. Words are separated by spaces. Handle multiple spaces between words.
Sample Input
Enter a sentence: Java is a powerful language
Sample Output
Word count: 5
Use nextLine() to read the sentence. Use split with regex to handle multiple spaces.
import java.util.Scanner;
public class WordCounter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String sentence = sc.nextLine().trim();
if (sentence.isEmpty()) {
System.out.println("Word count: 0");
} else {
String[] words = sentence.split("\\s+");
System.out.println("Word count: " + words.length);
}
sc.close();
}
}Challenge 4: Sum of N Numbers
MediumRead an integer N, then read N integers from the user. Print the sum, minimum, and maximum of those N integers.
Sample Input
Enter N: 5
Enter 5 numbers: 12 7 45 3 28
Sample Output
Sum: 95
Min: 3
Max: 45
Use a loop to read N numbers. Track min and max while reading.
import java.util.Scanner;
public class SumOfN {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter N: ");
int n = sc.nextInt();
System.out.print("Enter " + n + " numbers: ");
int sum = 0;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i = 0; i < n; i++) {
int num = sc.nextInt();
sum += num;
if (num < min) min = num;
if (num > max) max = num;
}
System.out.println("Sum: " + sum);
System.out.println("Min: " + min);
System.out.println("Max: " + max);
sc.close();
}
}Challenge 5: Input Validation Loop
MediumWrite a program that keeps asking the user for a valid integer between 1 and 100. If the input is not an integer or is out of range, print an error and ask again. Once valid input is received, print it.
Sample Input
Enter a number (1-100): abc
Invalid! Enter a number (1-100): 150
Out of range! Enter a number (1-100): 42
Sample Output
You entered: 42
Use hasNextInt() for type validation and a while loop for repeated input.
import java.util.Scanner;
public class ValidInput {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = 0;
boolean valid = false;
while (!valid) {
System.out.print("Enter a number (1-100): ");
if (sc.hasNextInt()) {
num = sc.nextInt();
if (num >= 1 && num <= 100) {
valid = true;
} else {
System.out.println("Out of range!");
}
} else {
System.out.println("Invalid!");
sc.next(); // consume invalid token
}
}
System.out.println("You entered: " + num);
sc.close();
}
}Challenge 6: Multi-Line Input Processor
HardUsing BufferedReader, read N (the first line), then read N lines of text. For each line, print the line number, the line itself, and the number of characters in it.
Sample Input
3
Hello World
Java
BufferedReader is fast
Sample Output
Line 1: Hello World (11 chars)
Line 2: Java (4 chars)
Line 3: BufferedReader is fast (21 chars)
Use BufferedReader only (not Scanner). Handle IOException.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class MultiLineProcessor {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine().trim());
for (int i = 1; i <= n; i++) {
String line = br.readLine();
System.out.println("Line " + i + ": " + line + " (" + line.length() + " chars)");
}
br.close();
}
}Challenge 7: Space-Separated Input Parser
HardRead a single line containing multiple integers separated by spaces. Without knowing how many integers there will be, compute the sum, average, and count of the numbers.
Sample Input
10 20 30 40 50
Sample Output
Count: 5
Sum: 150
Average: 30.0
Read the whole line with nextLine(), split by spaces, parse each part. Handle empty input.
import java.util.Scanner;
public class SpaceSeparated {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String line = sc.nextLine().trim();
if (line.isEmpty()) {
System.out.println("No input provided.");
} else {
String[] parts = line.split("\\s+");
int sum = 0;
int count = parts.length;
for (String part : parts) {
sum += Integer.parseInt(part);
}
double avg = (double) sum / count;
System.out.println("Count: " + count);
System.out.println("Sum: " + sum);
System.out.println("Average: " + avg);
}
sc.close();
}
}Challenge 8: Menu-Driven Calculator
HardBuild a menu-driven calculator that displays a menu (1. Add, 2. Subtract, 3. Multiply, 4. Divide, 5. Exit), reads the user's choice, reads two numbers if needed, performs the operation, and loops until the user chooses Exit. Validate all inputs.
Sample Input
Choice: 1
Enter two numbers: 15 25
Result: 40
Choice: 5
Sample Output
Result: 40
Goodbye!
Use a while loop with switch-case. Handle division by zero. Use proper Scanner techniques.
import java.util.Scanner;
public class MenuCalc {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
boolean running = true;
while (running) {
System.out.println("\n1. Add 2. Subtract 3. Multiply 4. Divide 5. Exit");
System.out.print("Choice: ");
int choice = sc.nextInt();
if (choice == 5) {
System.out.println("Goodbye!");
running = false;
} else if (choice >= 1 && choice <= 4) {
System.out.print("Enter two numbers: ");
double a = sc.nextDouble();
double b = sc.nextDouble();
switch (choice) {
case 1: System.out.println("Result: " + (a + b)); break;
case 2: System.out.println("Result: " + (a - b)); break;
case 3: System.out.println("Result: " + (a * b)); break;
case 4:
if (b == 0) System.out.println("Error: Division by zero!");
else System.out.println("Result: " + (a / b));
break;
}
} else {
System.out.println("Invalid choice!");
}
}
sc.close();
}
}Need to Review the Concepts?
Go back to the detailed notes for this chapter.
Read Chapter NotesWant to learn Java with a live mentor?
Explore our Java Masterclass