Explain Codes LogoExplain Codes Logo

Java: How to get input from System.console()

java
io-operations
exception-handling
best-practices
Nikita BarsukovbyNikita Barsukov·Nov 2, 2024
TLDR

To fetch user inputs in Java using System.console().readLine(), run the following code:

String input = System.console().readLine("Hey there! Kindly input something: "); System.out.println("Alright, you keyed in: " + input);

Note: For best experience, run this code directly in a terminal. Executing this in an IDE console can return null.

Handling null System.console()

At times, particularly when running Java apps in an IDE or a graphical environment, System.console() may return null. In such cases, the Console class might be unbootstrapped owing to an absent native platform console. Here's how to overcome this:

Savor the power of BufferedReader

BufferedReader, a class that facilitates the reading of text from an input stream such as System.in, buffers characters for an efficient reading of characters, arrays, and lines.

BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Hey there! Kindly input something: "); String s = br.readLine(); System.out.println("Alright, you keyed in: " + s);

Grace a Scanner for ease

Scanner class, another fan-favorite, is particularly handy for parsing types and strings. It works seamlessly with System.in:

Scanner in = new Scanner(System.in); System.out.print("Ready to feel old? Enter your age: "); //Just kidding! We all are getting older. int age = in.nextInt(); System.out.println("You are " + age + " years young. 😉"); //Aging is mandatory, growing up is optional. in.close();

Remember to close your Scanner instance to evade resource leaks.

Exception handling: No more tantrums

While converting user input to other data types, such as integers, always handle NumberFormatException to gracefully trap invalid entries:

try { int number = Integer.parseInt(input); } catch (NumberFormatException ex) { System.out.println("Oh-oh! That's not a valid integer. But A for effort!"); }

Consider good 'ol java.io.Console

For attendees from Java 6 and up, java.io.Console brings some advanced capabilities, such as password reading without echoing user input back on the console.

Console console = System.console(); if (console != null) { char[] password = console.readPassword("Key in your password: "); console.printf("Password entered: %s%n", new String(password)); //Don't worry! We're not peeking. }

Remember, like System.console().readLine(), certain methods of the Console class will also return null when used in a non-interactive environment.

Environment-specific adjustments

It's vital to design adaptive code that can behave both within and outside of an IDE while developing interactive Java applications. Here's how:

Top-level process execution

Ensure that your application runs as a top-level process in the console, failing which, System.console() won't return a non-null instance. Applications launched within an IDE typically lack a traditional console connection.

Acknowledge environment constraints

Different execution environments might have their limitations:

  • Java Web Start applications
  • Background services
  • Containers devoid of a pseudo-TTY

Each of these cases could, and would likely result in System.console() returning null.

The Swing in System.console()

When working with Swing for GUI applications, it's best to avoid System.console(). Rather, rely on text components within the user interface to take inputs.

Best practices, because why not?

Want to write robust code? These best practices have got you covered:

Efficient line reading

If you're all about efficiency (like us!), wrap System.in with a BufferedReader. Buffered input and line reading, check!

Exception handling

All I/O operations related exceptions and user inputs need to be trapped.

Prompting for input

Use System.out.print or console.printf to prompt the user pre-input reading.