{{announcement.body}}
{{announcement.title}}

The Less-Known API for Console Input in Java

DZone 's Guide to

The Less-Known API for Console Input in Java

With the presence of numerous GUI based and Web based apps, receiving input and data via console has reduced. But, there are applications that still run in a console.

· Java Zone ·
Free Resource

These days with the presence of numerous GUI based and Web based apps, receiving input and data via console has reduced. However, there are applications that require and run in a console. Java applications are not an exception to this. 

Getting input from the user was not as simple in Java as in other languages like scanf in C, cin in C++ and the input() method in Python. In the early days one had to write code like this

Java


The BufferedReader construct is itself enough to scare the newbie programmer of Java. 

However, from Java 6 - yes you heard me Java 6 - we had a new API that made getting console input much easier, but the programmer world mostly stuck to the old way and this was least known.

String input = System.console().readLine(); 

which is less scary than the previous one. In addition it also provides a C like format string based input reading as well for interactive input, so you could do something like

Java


When we run the code, we would see something like this

Shell


The other wonderful method of the console class is the readPassword() that enables to receive a password from the user with the echo disabled when the user types the password.

The Console class also provides the Reader object to read the usual way and also the Writer object. However, the catch is that it requires a terminal to run the main program. If it is run by a background task, the System.console() method returns null.

Happy coding!

Topics:
api, console, java

Published at DZone with permission of Prabhu Rengaswamy . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}