How do I use Console class to read user input?

In the previous example, How do I read user input from console using Scanner class?, we use the java.util.Scanner class to read user input. In this example we use another new class introduced in the Java 1.6, the class.

The Console class provide methods like readLine() and readPassword(). The readPassword() method can be use to read user’s password. Using this method the user’s input will not be shown in the console. The password will be returned as an array of char.



public class ConsoleDemo {

    public static void main(String[] args) {
        // Get a console object, console can be null if not available.
        Console console = System.console();

        if (console == null) {
            System.out.println("Console is not available.");

        // Read username from the console
        String username = console.readLine("Username: ");

        // Read password, the password will not be echoed to the
        // console screen and returned as an array of characters.
        char[] password = console.readPassword("Password: ");

        if (username.equals("admin") && String.valueOf(password).equals("secret")) {
            console.printf("Welcome to Java Application %1$s.%n", username);
        } else {
            console.printf("Invalid username or password.%n");

The result of the code snippet above is:

Username: admin
Welcome to Java Application admin.

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. If these posts help, you can support me, buy me a cup of coffee or tea. Thank you 🥳

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.