AdSense

AdSense3

Monday, 10 November 2014

Java Console class

The Java Console class is be used to get input from console. It provides methods to read text and password.

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. The Console class is introduced since 1.5.
Let's see a simple example to read text from console.
  1. String text=System.console().readLine();  
  2. System.out.println("Text is: "+text);  

Methods of Console class

Let's see the commonly used methods of Console class.
MethodDescription
1) public String readLine()is used to read a single line of text from the console.
2) public String readLine(String fmt,Object... args)it provides a formatted prompt then reads the single line of text from the console.
3) public char[] readPassword()is used to read password that is not being displayed on the console.
4) public char[] readPassword(String fmt,Object... args)it provides a formatted prompt then reads the password that is not being displayed on the console.

How to get the object of Console

System class provides a static method console() that returns the unique 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.*;  
  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: james gosling
Welcome james gosling

Java Console Example to read password

  1. import java.io.*;  
  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: sonoo

No comments:

Post a Comment