Java Program to take password from user in ***(astric) format.
Objective
Write a Java program to mask a password input with asterisks (*) in the console.
Algorithm / Approach
- Create and start a background
Threadwith an infinite loop that constantly prints a backspace\bfollowed by an asterisk*. - In the main thread, read the user's input character by character using
System.in.read(). - If the character is 13 (the Enter key), stop the asterisk thread and break the loop.
- Otherwise, append the character to the password string.
Test.java
public class Test
{
public static void main(String [] ar)
throws Exception {
Thread t = new Thread(){
public void run(){
while(true){
System.out.print("\b*");
}
}
};
t.start();
String s = "";
System.out.print("Enter Password: ");
while(true)
{
int i = System.in.read();
if(i==13){
t.stop();
break;
}
s += (char)i;
}
System.out.println("\bYour PWD: "+s);
}
}
Expected Output
Enter Password: ******* Your PWD: prowess
Explanation of the Program
- This is a clever console trick. Standard Java
System.inwill always echo (print) what the user is typing. - By running a secondary background thread that rapidly and continuously overwrites the terminal cursor with asterisks, it visually hides the characters the user is typing on the main thread.
- (Note: In modern Java, the
Console.readPassword()method is the preferred, secure way to do this).
Complexity
Time Complexity
O(n) - Where n is the password length.
Space Complexity
O(n)