Java Console Class
The Java Console class is used to get input from console. It provides
methods to read texts and passwords.
If you read password using Console class, it will not be displayed to the
user.
The java.io.Console class is attached with system console internally.
Let's see a simple example to read text from console.
1. String text=System.console().readLine();
2. System.out.println("Text is: "+text);
Java Console class declaration
Let's see the declaration for Java.io.Console class:
1. public final class Console extends Object implements Flushable
Java Console class methods
Method Description
Reader reader() It is used to retrieve the
reader object associated with the console
String readLine() It is used to read a single line of text from the
console.
String readLine(String fmt, It provides a formatted prompt then reads the
Object... args) single line of text from the console.
char[] readPassword() It is used to read password that is not being
displayed on the console.
char[] readPassword(String It provides a formatted prompt then reads the
fmt, Object... args) password that is not being displayed on the
console.
Console format(String fmt, It is used to write a formatted string to the
Object... args) console output stream.
Console printf(String It is used to write a string to the console output
format, Object... args) stream.
PrintWriter writer() It is used to retrieve the PrintWriter object
associated with the console.
void flush() It is used to flushes the console.
How to get the object of Console?
System class provides a static method console() that returns
the singleton instance of Console class.
1. public static Console console() {}
Let's see the code to get the instance of Console class.
1. Console c=System.console();
Java Console Example
1. import java.io.Console;
2. class ReadStringTest{
3. public static void main(String args[]){
4. Console c=System.console();
5. System.out.println("Enter your name: ");
6. String n=c.readLine();
7. System.out.println("Welcome "+n);
8. }
9. }
Output
Enter your name: Nakul Jain
Welcome Nakul Jain
Java Console Example to read password
1. import java.io.Console;
2. class ReadPasswordTest{
3. public static void main(String args[]){
4. Console c=System.console();
5. System.out.println("Enter password: ");
6. char[] ch=c.readPassword();
7. String pass=String.valueOf(ch);//converting char array into string
8. System.out.println("Password is: "+pass);
9. }
10. }
Output
Enter password:
Password is: 123