How to Read Input From Console in Java

If you have to read input from console in Java there are 3 options.

  1. Using BufferedReader class.
  2. Using Scanner class, available from Java 5.
  3. Using System.console() method, available from Java 6.

Using BufferedReader class

By wrapping the standard input stream “System.in” in an InputStreamReader which is further wrapped with in a BufferedReader you can read input from console in Java.

Output

Using Scanner class

Another option to read input from console in Java is to use Scanner class. A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values. For scanning input there are convenient methods for different data types like nextInt(), nextDouble(), nextFloat() etc.

Output

Using System.console method

You can also use System.console to read input from console in Java. One of the advantage of using System.console() method is that it returns a Console object which has a method readPassword() which can be used for reading a password or passphrase from the console with echoing disabled.

Output

Using System.console method to read password

Output

As you can see echoing for the password is disabled.

That’s all for the topic How to Read Input From Console in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.