Main Tutorials

Java – How to read input from System.console()

In Java, we can use System.console() to read input from the console.

JavaSample.java

package com.mkyong.io;

import java.io.Console;

public class JavaSample {

    public static void main(String[] args) {

        // jdk 1.6
        Console console = System.console();

        System.out.print("Enter your name: ");
        String name = console.readLine();
        System.out.println("Name is: " + name);

        System.out.print("Enter your password: ");

        // Reads a password from the console with echoing disabled
        char[] password = console.readPassword();
        String passwordStr = String.valueOf(password); // char[] to String;
        System.out.println("Password is: " + passwordStr);

    }

}

Output


Enter your name: mkyong
Name is: mkyong
Enter your password:
Password is: 123456

System.console() returns null in an IDE, try running it in the console or terminal.


$ cd project/target/classes

project/target/classes$ java com.mkyong.io.JavaSample
Enter your name: mkyong
Name is: mkyong
Enter your password:
Password is: 123456

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments