[Java] Java Console Input and Output Examples
Java Console Input and Output Examples
In this Java tutorial, learn different ways to read from and write to the system console. A console is generally connected with Java processes which are started using the command-line tool.
If the Java process has started automatically, (for example a background task), the console may not be available for input and output purposes.
1. Java read input from console
By default, to read from system console, we can use the
Console class. This class provides methods to access the character-based console, if any, associated with the current Java process. To get access to
Console, call the method System.console().
Console gives three ways to read the input:
Java program to read console input with readLine()
Java program to read console input with readPassword()
Java program to read console input with reader()
2. Java print output to console
The easiest way to write the output data to console is
System.out.println() statements. Still, we can use
printf() methods to write formatted text to console.
Java program to write to console with System.out.println
Java program to write to console with printf()
printf(String format, Object... args) method takes an output string and multiple parameters which are substituted in the given string to produce the formatted output content. This formatted output is written in the console.
The above listed methods for reading the input and writing output to the console provide alot of flexibility to read inputs in different formats and in different ways.
I will suggest you to play with given code to understand it better.
Happy Learning !!