Java Program to take input from user using DataInputStream.
Objective
Write a Java program to take input using DataInputStream (Legacy method).
Algorithm / Approach
- Import
java.io.DataInputStream. - Add
throws Exceptionto main. - Create a
DataInputStreamobject wrapped aroundSystem.in. - Use the deprecated
in.readLine()method to read text. - Use
Integer.parseInt()andDouble.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
DataInputStreamwas 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
ScannerorBufferedReaderfor 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.