Java Console Class


The Console class from the java.io package enables Java applications to perform console interactions such as reading user input and writing output. The Console class finds its primary application as a secure input method for passwords and a straightforward way to handle text output/input without using a graphical user interface.


notepad

In development environments such as Eclipse and IntelliJ, the Console object can return null. The Console object performs best when operated within an actual command-line environment.


Syntax:

import java.io.Console;
Console console = System.console(); 

Reading User Input

Read a String

String name = console.readLine("Enter your name: ");
System.out.println("Hello, " + name); 

Read Password (Masked Input)

char[] password = console.readPassword("Enter your password: ");
System.out.println("Password entered: " + String.valueOf(password)); 

notepad

The readPassword() function obscures user input and returns a character array to enhance security.


Example:

 import java.io.Console;

public class ConsoleExample {
  public static void main(String[] args) {
    Console console = System.console();

    if (console == null) {
      System.out.println("No console available. ");
      return;
    }

    String username = console.readLine("Enter your username: ");
    char[] password = console.readPassword("Enter your password: ");

    System.out.println("\nLogging in...");
    System.out.println("Username: " + username);
    System.out.println("Password: " + String.valueOf(password));
  }
}

Key Methods of Console Class

  • The readLine() function from the String class retrieves a line of text from the console.
  • The readLine method displays a formatted prompt to the user before accepting input.
  • The readPassword() method accepts a password input with masked visibility.
  • The char[] readPassword(String fmt, Object... args) method returns a char array after displaying a formatted prompt to the user.
  • The void printf(String fmt, Object... args)  method outputs formatted data similar to System.out.printf.
  • The reader() method gives access to a Reader for processing input streams.
  • The writer() method generates a Writer for the output stream.



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.