How to read input from console in Java

There are 3 different ways to read input from console in java. We can read input from console by using any one of the following Class.

Read Console Input using Scanner Class

Possibly this is the most preferred way to read input from console in java because of it’s simplicity and convenient methods like nextInt(), nextByte(), nextFloat(), nextLine() …etc it has to read targeted inputs. Application of this class is not just limited to reading input from console, it can operate on several types of data sources like String, File, InputStream, Readable, ReadableByteChannel and path.

Best thing is that regular expressions can be used to parse and retrieve tokens from input accordingly

Pros

  • Convenient methods (nextInt(), nextFloat(), nextByte()) to read primitive data types
  • Regular expressions can be used to read custom patterns.

Cons

Scanner class is not safe for multithreaded use since reading methods are not synchronized.

This Class is available to import at java.util.Scanner

Where System.in is Standard input stream which is by default console

Read Console Input using BufferedReader Class

This method was introduced in the JDK 1.0. This is relatively the complex way to read input compared to Scanner class. We have to use Both BufferedReader and InputStreamReader combined to read input from console. You can trade off this little complexity with efficiency.

Pros

This method of reading console input using BufferedReader is efficient.

Cons

Relatively complex code compared to other methods

Following Classes are required to import

java.io.BufferedReader
java.io.InputStreamReader

Read Console Input Using Console Class

The class Console was introduced in java 1.6. It is preferred way, if you plan to read secrets or passwords from command line since it provides the way to mask input through method readPassword(). Console class methods allow you to pass string for prompt as well which supports string formatting syntax. So you can use format specifiers like %s and %d in the format string.

Pros

  • Read password or secret phrases without echoing the entered characters on to console
  • Read and write operations are synchronized
  • String formatting can be used

Cons

  • It doesn’t work in non-interactive environments like IDE and jshell

Here is the complete code which demonstrates reading input from console by using above mentioned 3 ways ReadConsoleInput.java

Default image
neotam
Leave a Reply