C

Core Java tutorial for beginners

Clean • Professional

Core Java Input & Output – Using Scanner and BufferedReader

4 minute

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:

  1. Scanner (part of java.util)
  2. 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, Scanner is 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

MethodDescription
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

MethodDescription
readLine()Reads a line of text as String
close()Closes the reader

3. Scanner vs BufferedReader

FeatureScannerBufferedReader
PerformanceSlowerFaster
Ease of UseEasy (parses int, double, etc.)Slightly complex (needs parsing)
Exception HandlingNot neededMust handle IOException
Best Use CaseSmall programs, simple inputLarge 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

  1. Always close resources like Scanner or BufferedReader to avoid memory leaks.
  2. Use BufferedReader for large or high-performance input scenarios.
  3. Prefer Scanner for simple console-based programs and interviews.
  4. Avoid mixing nextInt() with nextLine() in Scanner without proper handling.
  5. Always handle exceptions when using BufferedReader.

🏆 Top 5 Java Interview Questions - Java I/O: Scanner & BufferedReader

1. Difference between Scanner and BufferedReader

Answer:

FeatureScannerBufferedReader
PurposeReads tokens (primitive types & strings)Reads text line by line efficiently
SpeedSlower (parses input)Faster (reads raw text)
Exception HandlingNo checked exceptionsThrows IOException
Input TypeCan read int, double, float, boolean, etc.Reads only strings; need parsing for numbers
ExampleScanner 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:

MethodDescriptionExample
next()Reads one token (up to whitespace)Input: Hello Worldnext() returns Hello
nextLine()Reads entire line, including spacesInput: Hello WorldnextLine() 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();

 

Article 0 of 0