Console input

The Console class allows the user to interact with a simple console application, using textual commands that you define.

Here's a simple example of its use:

import java.util.Arrays;
import java.io.Console;

/**
* Simple interactive console application.
* Uses the java.io.Console class of Java 6.
*/
public final class Console6 {

  public static final void main(String... args){
    Console console = System.console();
    //read user name, using java.util.Formatter syntax :
    String username = console.readLine("User Name? ");

    //read the password, without echoing the output 
    char[] password = console.readPassword("Password? ");

    //verify user name and password using some mechanism (elided)

    //the javadoc for the Console class recommends "zeroing-out" the password 
    //when finished verifying it :
    Arrays.fill(password, ' ');

    console.printf("Welcome, %1$s.", username);
    console.printf(NEW_LINE);

    String className = console.readLine("Please enter a package-qualified class name:");
    Class<?> theClass = null;
    try {
      theClass = Class.forName(className);
      console.printf("The inheritance tree: %1$s", getInheritanceTree(theClass));
    }
    catch(ClassNotFoundException ex){
      console.printf("Cannot find that class.");
    }

    //this version just exits, without asking the user for more input
    console.printf("Bye.");
  }
  
  // PRIVATE
  private static final String NEW_LINE = System.getProperty("line.separator");

  private static String getInheritanceTree(Class<?> aClass){
    StringBuilder superclasses = new StringBuilder();
    superclasses.append(NEW_LINE);
    Class<?> theClass = aClass;
    while (theClass != null) {
      superclasses.append(theClass);
      superclasses.append(NEW_LINE);
      theClass = theClass.getSuperclass();
    }
    superclasses.append(NEW_LINE);
    return superclasses.toString();
  }
} 

An example run:

>java  Console6
User Name? john
Password?
Welcome, john.
Please enter a package-qualified class name:java.util.ArrayList
The inheritance tree:
class java.util.ArrayList
class java.util.AbstractList
class java.util.AbstractCollection
class java.lang.Object

Bye.

JDK < 6

The Console class was added in Java 6. The following is an extended example of using an older version of the JDK. Here, input is read from the console in a continuous loop. As well, it has separated the problem into several parts, such that some parts can be reused in other console applications.

As in the previous example, the user inputs a package-qualified class name, and the corresponding inheritance tree is displayed.

An example run:

>java -cp . Console InheritanceInterpreter
Please enter a class name>as;k
Invalid.  Example:"java.lang.String">java.lang.String
The inheritance tree:
class java.lang.String
class java.lang.Object
Please enter a class name>
Invalid.  Example:"java.lang.String">
Invalid.  Example:"java.lang.String">....
Invalid.  Example:"java.lang.String">a;lskf
Invalid.  Example:"java.lang.String">java.sql.SQLWarning
The inheritance tree:
class java.sql.SQLWarning
class java.sql.SQLException
class java.lang.Exception
class java.lang.Throwable
class java.lang.Object
Please enter a class name>java.util.GregorianCalendar
The inheritance tree:
class java.util.GregorianCalendar
class java.util.Calendar
class java.lang.Object
Please enter a class name>exit

Bye.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
* Sends text back and forth between the command line and an
* Interpreter. 
*/
public final class Console {

  /**
  * Build and launch a specific <code>Interpreter</code>, whose
  * package-qualified name is passed in on the command line.
  */
  public static void main(String... args) {
    try {
      //unchecked cast:
      Class<Interpreter> theClass = (Class<Interpreter>)Class.forName(args[0]);
      Interpreter interpreter = theClass.getDeclaredConstructor().newInstance();
      Console console = new Console(interpreter);
      console.run();
    }
    catch (Exception ex){
      error(ex + " Cannot instantiate Interpreter.");
      error("Check class name, class path.");
    }
  }

  public Console(Interpreter interpreter) {
    this.interpreter = Objects.requireNonNull(interpreter);
  }

  /**
  * Display a prompt, wait for a full line of input, and then parse
  * the input using an Interpreter.
  *
  * Exit when <code>Interpreter.parseInput</code> returns true.
  */
  public void run() throws IOException {
    display(interpreter.getHelloPrompt());
    //pass each line of console input to the interpreter, 
    //and display its result
    try (
      InputStreamReader in = new InputStreamReader(System.in);
      BufferedReader stdin = new BufferedReader(in);
    ){
      boolean hasRequestedQuit = false;
      try {
        while(!hasRequestedQuit){
          List<Object> result = new ArrayList<Object>();
          String line = stdin.readLine();
          //interpret the line of input;
          //note that "result" is passed as an "out" parameter
          hasRequestedQuit = interpreter.parseInput(line, result);
          display(result);
        }
      }
      catch (IOException ex) {
        error(ex);
      }
    }
    finally {
      display(BYE);
    }
  }
  

  // PRIVATE
  private Interpreter interpreter;
  private static final String BYE = "Bye.";

  /**
  * Display some text to stdout.
  * The result of toString() is used.
  */
  private void display(Object thing){
    System.out.println(thing.toString());
  }
  
  private static void error(Object thing) {
    System.err.println(thing);
  }

  /**
  * Display a List of objects as text in stdout, in the order returned
  * by the iterator of aText.
  */
  private void display(List<Object> text) {
    text.forEach(p -> display(p));
  }
} 

import java.util.*;

/**
* Parse a line of text and return a result.
*/
public interface Interpreter {

  /**
  * @param line is non-null.
  * @param result is a non-null, empty List which acts as an "out"
  * parameter; when returned, result must contain a non-null, non-empty
  * List of items which all have a <code>toString</code> method, to be used
  * for displaying a result to the user.
  *
  * @return true if the user has requested to quit the Interpreter.
  * @exception IllegalArgumentException if a param does not comply.
  */
  boolean parseInput(String line, List<Object> result);

  /**
  * Return the text to be displayed upon start-up of the Interpreter.
  */
  String getHelloPrompt();
} 

import java.util.*;

/**
* Given a package-qualified class name, return the names of the classes in
* the inheritance tree.
*/
public final class InheritanceInterpreter implements Interpreter {

  /**
  * @param aLine is a non-null name of a class.
  * @param aResult is a non-null, empty List which acts as an "out"
  * parameter; when returned, aResult must contain a non-null, non-empty
  * List of class names which form the inheritance tree of the input class.
  *
  * @return true if the user has requeseted to quit the Interpreter.
  * @exception IllegalArgumentException if a param does not comply.
  */
  public boolean parseInput (String  aLine, final List aResult) {
    if (aResult == null) {
      throw new IllegalArgumentException("Result param cannot be null.");
    }
    if (!aResult.isEmpty()){
      throw new IllegalArgumentException("Result param must be empty.");
    }
    if (aLine == null) {
      throw new IllegalArgumentException("Line must not be null.");
    }

    boolean hasRequestedQuit = aLine.trim().equalsIgnoreCase(fQUIT) ||
                               aLine.trim().equalsIgnoreCase(fEXIT);
    if (hasRequestedQuit) {
      aResult.add(fNEW_LINE);
    }
    else {
      try {
        Class theClass = Class.forName(aLine);
        StringBuilder superclasses = new StringBuilder();
        superclasses.append(fHEADER);
        superclasses.append(fNEW_LINE);
        while (theClass != null) {
          superclasses.append(theClass);
          superclasses.append(fNEW_LINE);
          theClass = theClass.getSuperclass();
        }
        aResult.add(superclasses);
        aResult.add(fDEFAULT_PROMPT);
      }
      catch (ClassNotFoundException ex){
        //recover by asking the user for corrected input
        aResult.clear();
        aResult.add(fERROR_PROMPT);
      }
    }

    assert !aResult.isEmpty(): "Result must be non-empty.";

    return hasRequestedQuit;
  }

  /**
  * Return the text to be displayed upon start-up of the Interpreter.
  */
  public String getHelloPrompt() {
    return fHELLO_PROMPT;
  }

  // PRIVATE
  private static final String fHELLO_PROMPT = "Please enter a class name>";
  private static final String fDEFAULT_PROMPT = "Please enter a class name>";
  private static final String fERROR_PROMPT = "Invalid.  Example:\"java.lang.String\">";
  private static final String fHEADER = "The inheritance tree:";
  private static final String fQUIT = "quit";
  private static final String fEXIT = "exit";
  private static final String fNEW_LINE = System.getProperty("line.separator");
} 

See Also :
Get size of object in memory
Construct Object using class name