Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to take input using Console class.

Java Code Example — Input/Output Programs

ADVERTISEMENT

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

  1. Import java.io.Console.
  2. Get the system console instance: Console c = System.console();.
  3. Use c.readLine() to read normal text (like a username).
  4. Use c.readPassword() to securely read a password without echoing the characters to the screen.
  5. 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 Console class provides specialized features for terminal-based interactions that Scanner lacks.
  • Its most famous feature is readPassword(), which disables echoing in the terminal so bystanders cannot see what you are typing.
  • Notice that readPassword() returns a char[] array, not a String. 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)
ADVERTISEMENT