Java Program to take input from user using BufferedReader class.
Objective
Write a Java program to take input using BufferedReader and InputStreamReader.
Algorithm / Approach
- Import
java.io.*. - Add
throws Exceptionto the main method signature. - Create an
InputStreamReaderto translate bytes fromSystem.ininto characters. - Wrap it in a
BufferedReaderto buffer the characters for efficient reading of whole lines. - Use
in.readLine()to get string input, and manually parse it usingInteger.parseInt()for numbers.
InputDemo.java
import java.io.*;
class InputDemo{
public static void main(String[] a)
throws Exception
{
Reader r=new InputStreamReader(System.in);
BufferedReader in=new BufferedReader(r);
System.out.print("Enter Name: ");
String name = in.readLine();
System.out.print("Enter Age: ");
int age =Integer.parseInt(in.readLine());
System.out.print("Enter Marks: ");
double m=Double.parseDouble(in.readLine());
System.out.println("Name- "+name);
System.out.println("Age- "+age);
System.out.println("Marks- "+m);
}
}
Expected Output
Enter Name: Alok Enter Age: 23 Enter Marks: 71.2 Name- Alok Age- 23 Marks- 71.2
Explanation of the Program
- Before the
Scannerclass was introduced in Java 5,BufferedReaderwas the standard way to read console input. - It is still heavily used today because it is significantly faster than Scanner, making it the preferred choice for competitive programming where reading massive amounts of I/O data quickly is critical.
- However, it is less convenient: it only reads raw Strings, meaning you must manually parse all numeric data, and it throws checked
IOExceptionsthat must be handled.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)