![]() |
VOOZH | about |
Reading input from the console is a common requirement for building interactive programs. Java provides multiple ways to read user input in a command-line (console) environment. Each approach has its own use cases, advantages, and limitations depending on performance, simplicity, and environment.
Below are the commonly used ways to read input from the console in Java.
The BufferedReader class is the classical method to take input, introduced in JDK 1.0. This method is used by wrapping the System.in (standard input stream) in an InputStreamReader, which is wrapped in a BufferedReader. We can read input from the user in the command line.
Input:
Geek
Output:
Note: To read other types, we use functions like Integer.parseInt(), Double.parseDouble(). To read multiple values, we use split().
Scanner Class is probably the most preferred method to take input, Introduced in JDK 1.5. The main purpose of the Scanner class is to parse primitive types and strings using regular expressions; however, it is also can be used to read input from the user in the command line.
Input:
GeeksforGeeks
12
3.4
Output:
Console Class has been becoming a preferred way for reading userβs input from the command line, Introduced in JDK 1.6. In addition, it can be used for reading password-like input without echoing the characters entered by the user; the format string syntax can also be used (like System.out.printf()).
Input:
GeeksforGeeksOutput:
Advantages:
Limitations: Does not work in non-interactive environment (such as in an IDE).
Command line argument available since JDK 1.0, are used to pass inputs to a Java program at runtime, commonly in competitive coding. The inputs are stored as strings in the args[] array and can be converted to numeric values using methods like Integer.parseInt() or Float.parseFloat().
Command Line Arguments:
javac Geeks.java
java Main Hello WorldOutput:
DataInputStream class in Java (introduced in JDK 1.0) is used to read primitive data types from an input stream in a machine-independent format. It belongs to the java.io package and wraps an existing input stream, commonly used with DataOutputStream.
Input:
Enter an integer: 10
Enter a string: GeeksForGeeksOutput: