0

Can I ask that is there any method to display asterisk (*) when user input their password, and store the password entered as String value in Java ? Thanks

import java.util.*;

public class Log_in_form {

   Scanner scan=new Scanner(System.in);

   public static void main(String[] args) {

       String username="rosas";

       String password="sandy";


       System.out.println("Enter username");

       String user=scan.next();

       System.out.println("Enter password");

       String pass=scan.next();

     

       if(user.equals(username)&&(pass.equals(password))){

          System.out.println("Log in success");
       }

       else{

         System.out.println("log in failed");
       }

     }
    }
  • 1
    See https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/io/Console.html – k314159 Aug 27 '21 at 08:40
  • You should use char[] instead of String to handle passwords. See https://stackoverflow.com/questions/8881291/why-is-char-preferred-over-string-for-passwords – Abishek Stephen Aug 27 '21 at 08:48

1 Answers1

1

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

N/A

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.

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();      
      }
   }
}

For more details go through How to use Scanner to read silently from STDIN in Java?

Nagaraju Chitimilla
  • 530
  • 3
  • 7
  • 23