Wednesday, January 30, 2013

Java 6 Console Class



The Console Class is a new feature introduced in java 6 to get input from our console/keyboard. This Console class comes under the java.io package The main advantage of this class is reading passwords from console without displaying them.

import java.io.Console;
class ConsoleTest{
    public static void main(String arg[]){
        Console console = System.console(); // retrieves Console object 
        String userName=console .readLine("User name is : "); 
        char[] password=console .readPassword("Password is : ");
    }

Note:
- Using this readLine() method we can only read line of input given by users. In this Consle 
  class there are no methods to read an individual numbers or words like as in Scanner 
  class(nextInt() method).
- The readPassword() method returns array of characters due security reasons.
- You can execute this console class using command prompt not using eclipse.