Java read input from console

To capture input from console in Java program you have several options. Two of the most commons ones are to use Scanner (java.util.Scanner) or BufferedReader ( Both of them are using (standard input stream) to capture the keyboard input.

One thing to consider is that both classes Scanner and BufferedReader implement Closeable ( It is a good practice after reading the input to use the try/catch construction to release the resources. In case is closed, it cannot be opened again, so you should close the Scanner or the BufferedReader only after all the input from the user is done.

If we compare the performance of BufferedReader to that of the Scanner, the first is much faster but the second has more capabilities.

Read input with Scanner Class

You can use methods for getting specific input like Integer or Double. If the user does not provide this input, then the following exception is thrown: java.util.InputMismatchException

import java.util.Scanner;

public class MainClassTest {
    public static void main(String[] args) {
        // Use 'try' to close Scanner and release taken resources.
        // Connect the scanner to (keyboard)
        try(Scanner in = new Scanner(
            System.out.println("Please write string, integer and double: ");

            String s = in.nextLine();
            System.out.println("You entered string: " + s);

            int a = in.nextInt();
            System.out.println("You entered integer: " + a);

            double d = in.nextDouble();
            System.out.println("You entered double: " + d);

The input and the output of the program:

Please write string, integer and double: 
Test String
You entered string: Test String
You entered integer: 10
You entered double: 153.4

Read input with BufferedReader Class (standard input stream) is reading from InputStreamReader ( which is wrapped by BufferedReader ( This way we can use BufferedReader to read a whole line (row) with the method readLine().


public class MainClass {
    public static void main(String[] args) throws IOException {
        // Use 'try' to close BufferedReader and release taken resources.
        // Create InputStreamReader from (keyboard) and wrap in BufferedReader
        try(BufferedReader reader = new BufferedReader(new InputStreamReader(
            System.out.println("Please enter a sentence:");

            // With BufferedReader you can read whole line
            String line = reader.readLine();

            // Printing the read line
            System.out.println("The input is: " + line);

The input and the output of the program:

Please enter a sentence:
Hello Java
The input is: Hello Java

Leave a Comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.