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!!

1
  • get the length of g string and print * for that number of time. Commented Mar 27, 2020 at 3:48

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This will not run on IDE I think. You need to run it on Console
@kedarsedai Right, edited the answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.