The Java Console class facilitates obtaining input from the console, offering functionalities for reading both text and passwords.
When using the Console class to read passwords, the input will not be visible to the user as it is being entered.
The java.io.Console class is integrated with the system console internally. This class was introduced in version 1.5 of Java programming language.
Let's explore a basic illustration demonstrating how to retrieve input from the console.
String text=System.console().readLine();
System.out.println("Text is: "+text);
Java Console class declaration
Let's examine the declaration of the Java.io.Console class:
public final class Console extends Object implements Flushable
Java Console class methods
| Method | Description |
|---|---|
| Reader reader() | It is used to retrieve the readerobjectassociated with the console |
| String readLine() | It is used to read a single line of text from the console. |
| String readLine(String fmt, Object... args) | It provides a formatted prompt then reads the 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 fmt, Object... args) | It provides a formatted prompt then reads the password that is not being displayed on the console. |
| Console format(String fmt, Object... args) | It is used to write a formattedstringto the console output stream. |
| Console printf(String format, Object... args) | It is used to write a string to the console output stream. |
| PrintWriter writer() | It is used to retrieve thePrintWriterobject associated with the console. |
| void flush() | It is used to flushes the console. |
How to get the object of Console
The System class includes a static method called console which provides access to the sole instance of the Console class.
public static Console console(){}
Let's examine the code snippet that retrieves an instance of the Console class.
Console c=System.console();
Java Console Example
import java.io.Console;
class ReadStringTest{
public static void main(String args[]){
Console c=System.console();
System.out.println("Enter your name: ");
String n=c.readLine();
System.out.println("Welcome "+n);
}
}
Output
Enter your name: Nakul Jain
Welcome Nakul Jain
Java Console Example to read password
import java.io.Console;
class ReadPasswordTest{
public static void main(String args[]){
Console c=System.console();
System.out.println("Enter password: ");
char[] ch=c.readPassword();
String pass=String.valueOf(ch);//converting char array into string
System.out.println("Password is: "+pass);
}
}
Output
Enter password:
Password is: 123