Input / Output in Java using Scanner and BufferedReader
This guide covers user input handling in Java using both Scanner and BufferedReader, including examples, best practices, and comparison.
Introduction to Input in Java
In Java, you often need to read data from the user.
Two commonly used classes for this purpose are:
- Scanner (part of
java.util) - BufferedReader (part of
java.io)
Both allow reading text input, but have different use cases and performance characteristics.
1. Using Scanner Class
- Introduced in Java 5,
Scanneris easy to use and popular for console input. - Supports reading different types:
int,double,String, etc.
Import Scanner
import java.util.Scanner;
Example: Reading Basic Inputs
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine(); // read a line
System.out.print("Enter your age: ");
int age = sc.nextInt(); // read an integer
System.out.println("Name: " + name);
System.out.println("Age: " + age);
sc.close(); // close scanner
}
}
Output (User Input Example):
Enter your name: John
Enter your age: 25
Name: John
Age: 25
Scanner Methods
| Method | Description |
|---|---|
nextInt() | Reads an integer |
nextDouble() | Reads a double |
nextLine() | Reads a whole line of text |
next() | Reads a single word (space-delimited) |
nextBoolean() | Reads a boolean value |
Tip: After nextInt() or nextDouble(), use sc.nextLine() if you plan to read a line afterward to avoid skipping input.
2. Using BufferedReader Class
- Older, but faster than Scanner.
- Requires exception handling (
IOException). - Reads input as String, then you convert to other types.
Import BufferedReader
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
Example: Reading Input
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your name: ");
String name = br.readLine();
System.out.print("Enter your age: ");
int age = Integer.parseInt(br.readLine()); // convert string to int
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
Output (User Input Example):
Enter your name: Alice
Enter your age: 30
Name: Alice
Age: 30
BufferedReader Methods
| Method | Description |
|---|---|
readLine() | Reads a line of text as String |
close() | Closes the reader |
3. Scanner vs BufferedReader
| Feature | Scanner | BufferedReader |
|---|---|---|
| Performance | Slower | Faster |
| Ease of Use | Easy (parses int, double, etc.) | Slightly complex (needs parsing) |
| Exception Handling | Not needed | Must handle IOException |
| Best Use Case | Small programs, simple input | Large input, performance-sensitive programs |
4. Example – Reading Multiple Inputs
import java.util.Scanner;
public class MultipleInputExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter 3 numbers: ");
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int sum = a + b + c;
System.out.println("Sum: " + sum);
sc.close();
}
}
Sample Input / Output:
Enter 3 numbers: 10 20 30
Sum: 60
Best Practices
- Always close resources like
ScannerorBufferedReaderto avoid memory leaks. - Use BufferedReader for large or high-performance input scenarios.
- Prefer Scanner for simple console-based programs and interviews.
- Avoid mixing
nextInt()withnextLine()in Scanner without proper handling. - Always handle exceptions when using BufferedReader.
🏆 Top 5 Java Interview Questions - Java I/O: Scanner & BufferedReader
1. Difference between Scanner and BufferedReader
Answer:
| Feature | Scanner | BufferedReader |
|---|---|---|
| Purpose | Reads tokens (primitive types & strings) | Reads text line by line efficiently |
| Speed | Slower (parses input) | Faster (reads raw text) |
| Exception Handling | No checked exceptions | Throws IOException |
| Input Type | Can read int, double, float, boolean, etc. | Reads only strings; need parsing for numbers |
| Example | Scanner sc = new Scanner(System.in); | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
2. How do you read integers using BufferedReader?
Answer: BufferedReader reads input as strings, so you need to parse it into integers using Integer.parseInt():
import java.io.*;
public class InputExample {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter an integer: ");
int num = Integer.parseInt(br.readLine());
System.out.println("You entered: " + num);
br.close();
}
}
3. What is the difference between next() and nextLine() in Scanner?
Answer:
| Method | Description | Example |
|---|---|---|
next() | Reads one token (up to whitespace) | Input: Hello World → next() returns Hello |
nextLine() | Reads entire line, including spaces | Input: Hello World → nextLine() returns Hello World |
4. Why do we need to close Scanner or BufferedReader?
Answer:
- Closing releases system resources associated with the stream.
- Prevents memory leaks in large applications.
- For Scanner:
sc.close() - For BufferedReader:
br.close()
Note: Do not close Scanner(System.in) in some applications where System.in is reused, as it will close standard input.
5. When should you prefer BufferedReader over Scanner?
Answer:
- Performance: BufferedReader is faster for large inputs or line-based reading.
- Complex Parsing: When you don’t need token parsing, just reading full lines.
- Exceptions: If you want checked exception handling (
IOException) for robust input handling.
Example Use Case: Reading multiple lines from a file or console input efficiently.
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
