Quick revision
The short answer
Interactive password input should go through Console.readPassword(), which turns off echo and returns a char array we can wipe, and only when the program really runs in a terminal. In CI and other non-interactive runs, the tool should never prompt: it should take the secret from an environment variable, a permission-restricted file or a secrets manager, and fail fast with a clear message if none is supplied. A CLI library such as picocli gives us options, help text and masked prompts without writing the plumbing ourselves.
What to remember
In this answer, we saw that Scanner both echoes the password and blocks forever when there is no person to type. We replaced it with Console.readPassword, which hides input and returns a char array we wipe, used only after checking that a real terminal is attached. We designed a documented order of non-interactive sources, a file with strict permissions, an environment variable and a secrets manager, with a fast, clear failure when none is present, and used picocli for consistent options and masked prompts.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Interactive password input should go through Console.readPassword(), which turns off echo and returns a char array we can wipe, and only when the program really runs in a terminal. In CI and other non-interactive runs, the tool should never prompt: it should take the secret from an environment variable, a permission-restricted file or a secrets manager, and fail fast with a clear message if none is supplied. A CLI library such as picocli gives us options, help text and masked prompts without writing the plumbing ourselves.
Why this question is asked
Small internal tools often start as a quick main method and grow into something many teams run, including from pipelines. A tool that echoes a database password to the screen leaks it into terminal scrollback, screen shares and recordings, and a tool that waits for input in CI blocks a build agent until a timeout kills it, often an hour later. Interviewers ask this to see whether we think about where a program runs, not just what it does. In this answer, we will see why the current tool echoes and hangs, use Console to read a password safely, detect non-interactive runs, design the order in which the tool looks for its secret, and handle the secret carefully in memory.
1Why the Current Tool Echoes and Hangs
Scanner reads from System.in, a plain stream of bytes. It knows nothing about terminals, so it cannot turn off echo: the terminal shows every character the user types, password included.
In CI there is no person at a keyboard. Depending on how the job runner sets up standard input, it may be connected to something that never sends data and never reaches end of file. Scanner's nextLine() then blocks forever, waiting for a line that will never come. The tool does not crash, it simply sits there until the job's timeout, which is the worst kind of failure to diagnose.
2Reading a Password With Console
java.io.Console represents the terminal the program is attached to. Its readPassword() method switches off echo while the user types and returns the password as a char array, not a String.
The char array matters because a String is immutable: once created it stays in memory until the garbage collector reclaims it, and it may end up in heap dumps. A char array can be overwritten the moment we no longer need it. It is not perfect protection, since the JDBC driver may still copy the value, but it shortens the window.
Detecting a terminal changed in recent Java versions. Traditionally System.console() returned null when there was no interactive terminal, for example when input was redirected or the program ran in CI. Since JDK 22 it can return a Console object even then, and Console.isTerminal() tells us whether it is really attached to a terminal. So on Java 25 we check both, as above; check your version if you support older JVMs.
3Designing Non-Interactive Input First
Prompting should be the last resort, not the default. Automation needs a way to pass the secret without a person, and the tool should look for it in a fixed, documented order. A command-line argument like --password=secret is not one of those ways: arguments are visible to other users through process listings and end up in shell history and CI logs.
- --password-file given?Yesread the file; refuse it if others can read itNonext source
- DB_PASSWORD environment variable set?Yesuse it (CI injects it from its secret store)Nonext source
- Secrets manager configured?Yesfetch it, e.g. from Vault or a cloud secret storeNonext source
- Real interactive terminal?Yesprompt with readPassword, echo offNoexit 2 with a clear message
4 steps in order. Play them, or step through them one at a time.
So in CI, the pipeline injects DB_PASSWORD from its own secret store, the tool picks it up and never touches standard input. On a laptop, a developer with nothing configured gets a masked prompt. And if a pipeline is misconfigured, the job fails in a second with a message that says exactly what to set, instead of hanging for an hour.
For the password file, we check that it is readable only by its owner (for example POSIX permissions rw-------, read with Files.getPosixFilePermissions) and refuse it otherwise, the same way ssh refuses a private key that others can read.
4Using picocli Instead of Hand-Written Parsing
Once a tool has several inputs, flags and help text, writing the parsing by hand becomes its own source of bugs. picocli is a widely used library that turns annotated fields into a full command line interface, including masked interactive prompts.
With interactive = true, picocli prompts with echo turned off when the option is given without a value. We still apply our own source order and the terminal check, but the help text, validation and error messages come for free and look the same across the team's tools.
5Handling the Secret Carefully Everywhere Else
The rest of the tool must not undo the care taken at input. We never log the password or include it in exception messages, connection strings or debug output. We avoid converting it to a String just to pass it along, and wipe the char array in a finally block. If the tool prints its effective configuration, the password shows as a fixed mask. Finally, we add a test that runs the tool with standard input closed and no secret configured, and asserts that it exits quickly with code 2, so the CI hang can never come back unnoticed.
6Follow-up questions
Why not just add a timeout to the Scanner read?
Because a timeout only turns a one-hour hang into a one-minute hang, and still prompts in places where nobody can answer. The real fix is to know whether we are interactive and to have a non-interactive path. Blocking reads on System.in also cannot be interrupted cleanly.
Is an environment variable safe enough for a password?
It is the usual way CI systems inject secrets, and they mask it in logs. It can still be read by processes running as the same user, so for higher-risk secrets a secrets manager with short-lived credentials is better. Either way it is far safer than a command-line argument.
Why does readPassword return char[] rather than String?
So we can erase it. A String cannot be changed and lives until garbage collection, possibly showing up in heap dumps; a char array can be filled with zeros immediately after use.
7Conclusion
In this answer, we saw that Scanner both echoes the password and blocks forever when there is no person to type. We replaced it with Console.readPassword, which hides input and returns a char array we wipe, used only after checking that a real terminal is attached. We designed a documented order of non-interactive sources, a file with strict permissions, an environment variable and a secrets manager, with a fast, clear failure when none is present, and used picocli for consistent options and masked prompts.
Open with
There are two problems: the password is echoed because Scanner just reads bytes and cannot control the terminal, and in CI it hangs because nextLine waits forever for input nobody will type.
Then, if they want more
For the interactive case, I would use System.console().readPassword, which turns echo off and returns a char array I can wipe with Arrays.fill once I have connected.
But I would only prompt when there really is a terminal: traditionally System.console() returns null when input is redirected, and since JDK 22 I also check Console.isTerminal, because it can return a console object anyway. For automation the tool should never prompt.
I would define an order: a password file whose permissions I check, then an environment variable such as DB_PASSWORD that the CI system injects from its secret store, then a secrets manager, and only then a masked prompt; if none applies and there is no terminal, exit immediately with a clear message and a non-zero code, so the pipeline fails in seconds instead of hanging.
I would not accept the password as a command-line argument, because it shows up in process lists and logs. I would move the parsing to picocli, which supports interactive masked options and gives consistent help.
And I would make sure the password is never logged, never put in a String unnecessarily, and add a test that runs the tool with no input and checks it fails fast.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 22, Java 25
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "An internal Java CLI prompts for a database password with Scanner and echoes it on...": https://scrivio-interview-library.netlify.app/java/io-and-nio/5a66cb86ab/