This Java tutorial helps you understand the java.io.Console class which provides convenient methods for reading input and writing output to the standard input (keyboard) and output streams (display) in command-line (console) programs.

As the Java platform evolves over the years, it introduces the Console class (since Java 6) which is more convenient to work with the standard input/output streams than the traditional approach (using System.in and System.out).

Consider the following code before Java 6:

BufferedReader standardInput
	= new BufferedReader(new InputStreamReader(System.in));

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

Imagine you can shorten this piece of code:

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

by this one using the Console class:

String name = console.readLine("Enter your name: ");
console.printf("Hello %s ", name);

As you can see, we can both read input and write output using this class conveniently.

Now, let’s look at deeper into using this class.

 

1. Obtaining the Console instance

We obtain the unique instance of the Console class via the static method console() of the System class like this:

Console console = System.console();

However this method returns null if the program is running in non-interactive environment such as inside an IDE, so we need to check to ensure that the Console is actually available for use:

if (console == null) {
	System.out.println("Console is not supported");
	System.exit(1);
}

 

2. The Console’s methods for input and output

Then we can use the following methods for dealing with the standard input/output streams:

  • format(String fmt, Object... args): works same as System.out.format()
  • printf(String format, Object... args): works same as System.out.printf()
  • readLine() : works same as BufferedReader.readLine()
  • readLine(String fmt, Object... args): prints a formatted string and reads input
  • readPassword(): reads a password to a char array
  • readPassword(String fmt, Object... args): prints a formatted string and reads a password to a char array

 

The method readPassword() is very interesting and useful, as it allows a program to read a password from the user securely:

  • First, it suppresses echoing, so the password is not visible on the user's screen.
  • Second, readPassword() returns a character array, not a String, so the password can be overwritten, removing it from memory as soon as it is no longer needed.

In addition, all these methods are synchronized to guarantee the atomic completion of critical operations.

 

3. Using Console for Input and Output Example

The following program demonstrates how to use the Console class to read input data from the user and print output:

import java.io.*;
import java.util.*;

/**
 * This program demonstrates how to use the Console class to read input
 * and write output in command-line interface.
 *
 * @author www.codejava.net
 */
public class ConsoleInputOutputExample {

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

		if (console == null) {
			System.out.println("Console is not supported");
			System.exit(1);
		}

		String name = console.readLine("What's your name? ");
		String age = console.readLine("How old are you? ");
		String city = console.readLine("Where do you live? ");

		console.format("%s, a %s year-old man is living in %s", name, age, city);
	}
}

Run this program and enter some input like this:

What's your name? John
How old are you? 40
Where do you live? California

And you will see the result:

John, a 40 year-old man is living in California

 

4. Using Console for Reading Password Example

The following program demonstrates using the Console class to read login information from the user:

import java.io.*;
import java.util.*;

/**
 * This program demonstrates how to use the Console class to read a
 * password securely.
 *
 * @author www.codejava.net
 */
public class ConsoleLoginExample {

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

		if (console == null) {
			System.out.println("Console is not supported");
			System.exit(1);
		}

		console.printf("Welcome to Java Expert Program!\n");
		String name = console.readLine("Enter your name: ");
		char[] password = console.readPassword("Enter your password: ");

		char[] correctPassword = {'n', 'i', 'm', 'd', 'a'};

		if (Arrays.equals(password, correctPassword)) {
			console.printf("Thanks %s, you are logged in.\n", name);
		} else {
			console.printf("Sorry, you are denied.\n");
		}

		Arrays.fill(password, ' ');
		Arrays.fill(correctPassword, ' ');
	}
}

Pay attention to the last two statements: 

Arrays.fill(password, ' ');
Arrays.fill(correctPassword, ' ');

This clears the password arrays for security purpose.

Run this program, enter your name and password as ‘nimda’, you will see the following result:

Welcome to Java Expert Program!
Enter your name: John
Enter your password:
Thanks John, you are logged in.

 

API Reference:

 Console class Javadoc

 

Related Tutorials:

 

Other Java File IO Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment

   


Comments 

#3Umesh2018-01-29 01:08
How to show program output of console in a bold letters
Quote
#2Nam2017-09-03 15:41
Hi Anvil,
Thanks for your feedback. I will update the article as per your request because your comment really caught my attention.
Quote
#1Anvil2017-08-31 15:02
If my daughter tries to learn Java and runs your example, she gets
Sarah, a 9 year-old man is living in New York

While this may not seem like a big deal, there are already a lot of barriers to women entering tech, and assumptions like this (which individually aren't that bad) add up to create a toxic environment. Please change "man" to "person."
Quote