Console Class In Java
Console Class
Console class is used to get the input from console. It provides the methods to read the text and password.
If we read password, using Console class, it will not be displayed to the user.
Internally, java.io.Console class is attached with the system console and it is introduced since 1.5.
Methods of Console class
public String readLine()
This method is used to read a single line of text from the console.
public String readLine(String fmt,Object... args)
This method is used provide a formatted prompt, followed by reading the single line of the text from the console.
public char[] readPassword()
This method is used to read the password that is not being displayed on the console.
public char[] readPassword(String fmt,Object... args)
This method is used to provide a formatted prompt, followed by reading the password that is not being displayed on the console.
How to get the object of Console
System class provides a static method console() which returns the unique instance of Console class.
public static Console console(){}
Code to get the object of Console class.
Console c=System.console();
Let’s see an example.
Code
- import java.io.*;
- public class ConsoleClass {
- public static void main(String args[]) {
- Console c = System.console();
- System.out.println("please enter your name: ");
- String name = c.readLine();
- System.out.println("Hello, " + name);
- }
- }
Output
Summary
Thus, we learnt that Console class is used to get the input from console. It provides the methods to read the text and password and also learnt its important methods in Java.