Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to take password from user in ***(astric) format.

Java Code Example — Utility Programs

ADVERTISEMENT

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

  1. Create and start a background Thread with an infinite loop that constantly prints a backspace \b followed by an asterisk *.
  2. In the main thread, read the user's input character by character using System.in.read().
  3. If the character is 13 (the Enter key), stop the asterisk thread and break the loop.
  4. 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.in will 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)
ADVERTISEMENT