How to read input from console in Java

This tutorial shows several ways for reading input from a console in Java.

Before listing the ways, it’s worth to define System.in as it’s used by most reading ways.

System.in is a static field of type InputStream representing the stream which corresponds to keyboard input or any other input source specified by the host machine.

1- BufferedReader

The oldest way of reading input from console in Java is through BufferedReader which is introduced in JDK 1.0. To do so, we use InputStreamReader and System.in as the following:

2- Scanner

The most popular way of reading input from console in Java is through Scanner object which is introduced in JDK 1.5. Scanner also uses System.in and provides several utility methods for reading input of specific types.

Some of the common methods provided by Scanner:

  • next(): this method reads the next String token as per the defined delimiter. (the default delimiter is space)
  • nextLine(): this method reads the remaining input from the current cursor till the end of the line.
  • nextInt(): this method reads the next integer provided in the input. If no integer is provided then InputMismatchException is thrown.
  • nextDouble(): this method reads the next double provided in the input. If no double is provided then InputMismatchException is thrown.

3- System.console

This is the modern way of reading input from console in Java, it’s introduced in JDK 1.6 and allows developers to read input without using System.in. The drawback of using this technique is that it doesn’t work under IDE and only works in interactive environments.

 

Hussein Terek

Founder of programmergate.com, I have a passion in software engineering and everything related to java environment.

You may also like...

Leave a Reply

avatar