How many ways can you take input from the console in Java?
Last Updated on :April 14, 2021
In Java, there are three different ways for reading input from the user in the command line environment(console).
1. Using Buffered Reader Class: 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.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) throws IOException {
//Enter data using BufferReader
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// Reading data using readLine
String name = reader.readLine();
// Printing the read line
System.out.println(name);
}
}
2. Using Scanner Class: The main purpose of the Scanner class is to parse primitive types and strings using regular expressions, however it can also be used to read input from the user in the command line.
import java.util.Scanner;
public class Test {
public static void main(String args[]) {
// Using Scanner for Getting Input from User
Scanner in = new Scanner(System.in);
String s = in.nextLine();
System.out.println("You entered string " + s);
int a = in.nextInt();
System.out.println("You entered integer " + a);
float b = in.nextFloat();
System.out.println("You entered float " + b);
}
}
3. Using Console Class: It has been becoming a preferred way for reading user’s input from the command line.
Please note that If there is no console associated with the javadoc, then System.console() returns null hence the program will throw NullPointerException.
You can use above approach like Bufferedreader Class or Scanner Class to read input from console
public class Test
{
public static void main(String[] args) {
// Using Console to input data from user
String name = System.console().readLine();
System.out.println(name);
}
}