Getty Images/iStockphoto

How Java's System.in reads input from the user

The Java System.in component provides universal access to console-based user input. Learn how to make your applications interactive with this Java System.in tutorial.

What is System.in?

In Java, System.in is the standard, universally accessible InputStream that developers use to read input from the terminal window.

However, Java's System.in does not work alone. To read user input with System.in, you must pass it as an argument to either:

  1. The constructor of the Scanner class
  2. The constructor of an InputStreamReader

System.in and Java's Scanner class

The easiest way to read input from the user with System.in is to use the Scanner class.

The following code prompts the user for their name, consumes keyboard input and prints out a response to the client:

System.out.println("What is your name?");

Scanner scanner = new Scanner(System.in);

String name = scanner.nextLine();

System.out.println(name + " is a nice name!");

System.in and Java's BufferedStreamReader

Without the Scanner class, reading user input with System.in is more complicated, and instead uses the InputStreamReader to convert data from bytes to characters. To do this, you must pass Java's System.in to the constructor of an InputStreamReader, and then pass that to the BufferedReader.

The code below shows how to get user input with System.in, the InputStreamReader and the BufferedReader:

InputStreamReader reader = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(reader);

System.out.println("Whis is our name?");

var input = br.readline();

System.out.println("Your input was: " + input);

Regardless of whether you go the path of the Scanner, or combine the BufferedReader with the InputStreamReader, Java's System.in InputStream is always at the heart of console-based input in the JVM.

Dig Deeper on JSRs and APIs

App Architecture
Software Quality
Cloud Computing
Security
SearchAWS
Close