Java.io.Console.readPassword() Method


Advertisements


Description

The java.io.Console.readPassword() method reads a password from the console with echoing disabled.

Declaration

Following is the declaration for java.io.Console.readPassword() method −

public char[] readPassword()

Parameters

NA

Return Value

This method returns a character array containing the password read from the console, not including the line termination character, or null if an end of stream has been reached.

Exception

IOError − If an I/O error occurs.

Example

The following example shows the usage of java.io.Console.readPassword() method.

package com.tutorialspoint;

import java.io.Console;

public class ConsoleDemo {

   public static void main(String[] args) {      
      Console cnsl = null;
      String alpha = null;
      
      try {
      
         // creates a console object
         cnsl = System.console();

         // if console is not null
         if (cnsl != null) {
            
            // read line from the user input
            alpha = cnsl.readLine("Name: ");
            
            // prints
            System.out.println("Name is: " + alpha);
            
            // read password into the char array
            char[] pwd = cnsl.readPassword("Password: ");
            
            // prints
            System.out.println("Password is: "+pwd);
         } 
         
      } catch(Exception ex) {
         
         // if any error occurs
         ex.printStackTrace();      
      }
   }
}

Let us compile and run the above program, this will produce the following result −

Name: Master Programmer
Name is: Master Programmer
Password: 
Password is: Good Morning

java_io_console.htm

Advertisements