Java Program to take input using Console class.
Objective
Write a Java program to read sensitive data (like passwords) using the Console class.
Algorithm / Approach
- Import
java.io.Console. - Get the system console instance:
Console c = System.console();. - Use
c.readLine()to read normal text (like a username). - Use
c.readPassword()to securely read a password without echoing the characters to the screen. - Convert the resulting character array into a String and print it (for demonstration purposes).
InputDemo.java
import java.io.Console;
class InputDemo{
public static void main(String[] a)
{
Console c = System.console();
System.out.print("Enter name: ");
String name = c.readLine();
System.out.print("Enter password: ");
char[] pas = c.readPassword();
String pass = new String(pas);
System.out.println("Name- "+name);
System.out.println("Password- "+pass);
}
}
Expected Output
Enter name: ayan Enter password: (NOT VISIBLE) Name- ayan Password- 1234
Explanation of the Program
- The
Consoleclass provides specialized features for terminal-based interactions thatScannerlacks. - Its most famous feature is
readPassword(), which disables echoing in the terminal so bystanders cannot see what you are typing. - Notice that
readPassword()returns achar[]array, not aString. This is a security feature. Strings are immutable and stay in memory for a long time, whereas a character array can be manually wiped (overwritten with blank spaces) immediately after use to prevent memory scraping.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)