Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to take input from user using DataInputStream.

Java Code Example — Input/Output Programs

ADVERTISEMENT

Java Program to take input from user using DataInputStream.

Objective

Write a Java program to take input using DataInputStream (Legacy method).

Algorithm / Approach

  1. Import java.io.DataInputStream.
  2. Add throws Exception to main.
  3. Create a DataInputStream object wrapped around System.in.
  4. Use the deprecated in.readLine() method to read text.
  5. Use Integer.parseInt() and Double.parseDouble() to handle numeric conversions.
InputDemo.java
import java.io.DataInputStream;
class InputDemo {
 public static void main(String[] a)
  throws Exception
 {
  DataInputStream in =null;
  in = new DataInputStream(System.in);
  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

  • DataInputStream was one of the earliest ways to read input in Java (dating back to Java 1.0).
  • Its readLine() method has been officially deprecated since Java 1.1 because it does not properly convert bytes to characters (it fails with certain international character sets).
  • While you will still see this taught in some older academic curriculums, modern Java developers should strictly use Scanner or BufferedReader for reading text.

Complexity

Time Complexity O(1)
Space Complexity O(1)

Common Mistakes

  • Using this class for reading text in production code. It should only be used for reading primitive Java data types (like raw bytes or ints) from binary streams.
ADVERTISEMENT