0

Uses Case : My objective is whenever user tries to give user input (for ex: password) in console output screen instead of password text (For ex in output console : Enter the password :******** (but the password is Qwerty@123,but when user types Qwerty@123 it should get replaced by ********* in console)), astericks should get displayed.Is it possible to do,i have seen some video as well based on password encryption in java but did'nt found anything related to my question.

import java.util.*;

public class abc {

    public static void main(String args[]) {
        String g;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the password : ");
        g = sc.nextLine();
    }
}

Output i am getting: Enter the password : Qwerty@123

Output what i am excepting: Enter the password : ********** should get typed while user types Qwerty@123

Please let me know if question asked is not a clear. Thanks in advance, be safe!!

Jerome Wolff
  • 356
  • 3
  • 19

1 Answers1

0

JDK provides Console class to handle these scenarios, it provides readPassword to read password by masking, it doesn't display *'s though.

Here is a small example.

import java.io.Console;
public class Library {
public static void main(String[] args) {
    Console console = System.console();
    char[] passwordArray = console.readPassword("Enter your password: ");
    console.printf("Password is: %s%n", new String(passwordArray));
}
}

Note: This only works with System's console, doesn't work with IDE.

raviraja
  • 676
  • 10
  • 27