How to read interactive command-line input with Java

Java command-line FAQ: How do I read command line input from a Java application (interactively)?

Solution: As of Java 5 (and newer Java versions), the best way to solve this problem is to use the Java Scanner class. Before I show how to use the Scanner class, here’s a short description of what it does from its Javadoc:

“A simple text scanner which can parse primitive types and strings using regular expressions. A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.”

A Java Scanner class example

The following source code shows how to create and use a Java Scanner instance to read command-line input:

import java.util.Scanner;

 * A Java Scanner class example from
public class JavaScannerExample

  public static void main (String[] args)
    // create a scanner so we can read the command-line input
    Scanner scanner = new Scanner(;

    //  prompt for the user's name
    System.out.print("Enter your name: ");

    // get their input as a String
    String username =;

    // prompt for their age
    System.out.print("Enter your age: ");

    // get the age as an int
    int age = scanner.nextInt();

    System.out.println(String.format("%s, your age is %d", username, age));



When you run this program the command-line interaction looks like this:

Enter your name: Al
Enter your age: 42
Al, your age is 42

Note that the next* methods of the Scanner class can throw exceptions that you'll need to handle. This is demonstrated in the following example, where I intentionally don’t enter an int value for the age:

Enter your name: Al
Enter your age: Fred
[error] (run-main-0) java.util.InputMismatchException
	at java.util.Scanner.throwFor(
	at java.util.Scanner.nextInt(
	at java.util.Scanner.nextInt(
	at ScannerTest.main(
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(
	at java.lang.reflect.Method.invoke(

The Scanner class “next” methods

The Scanner class has a collection of next* methods that you can use to read a users’ command-line input. Some of the most common methods are shown here:

next           finds and returns the next complete token from this scanner
next(pattern)  returns the next token if it matches the specified pattern
nextBoolean    returns true if the next token in this scanner's input can be interpreted 
               as a boolean value using a case insensitive pattern created from the string "true|false"
nextByte       scans the next token of the input as a byte
nextDouble     scans the next token of the input as a double
nextFloat      scans the next token of the input as a float
nextInt        scans the next token of the input as an int
nextLine       advances this scanner past the current line and returns the input that was skipped
nextLong       scans the next token of the input as a long
nextShort      scans the next token of the input as a short

It’s fairly obvious how most of those methods work if you’re prompting a user for one input value at a time, but things can get interesting when you use pattern-matching to parse user input.

The Javadoc shows a little bit about how to use pattern-matching with a Scanner, but IMHO it’s not a good idea to use regex patterns when trying to read interactive command-line input. There are a lot of things that can go wrong when you’re reading user input, and when you try to match interactive command-line input against a regex, well, let’s just say that you’ll need to handle a lot of exceptions. Whenever I do this I just tend to read the user’s input as a String, and then I try to parse that String once I have it.

As a final note, I want to reiterate that all of these methods can throw exceptions, as I demonstrated in the example above.

Reading Java command-line input in the good old days

As a quick note, while this is now basically legacy information, if you want to see how we read command line input in Java in the days before Java 5, see my article titled, Java code to read command-line input.



This helped me substantially! A well explained and accurate example, thanks!


Can you please explain as to why do we use the as an input to InputStreamReader, and the InputStreamReader as an input to BufferedReader.

Sure. represents the standard input stream. As the System Javadoc states, "This stream is already open and ready to supply input data. Typically this stream corresponds to keyboard input or another input source specified by the host environment or user." So that's where we start to get the keyboard input.

The InputStreamReader is the "bridge from byte streams to character streams", so it helps perform that conversion, as I want to deal with keystrokes as characters in my code, and not bytes. (A different programmer might want to deal with them as bytes, but because I know I want to use the BufferedReader's readLine() method, I'm going down this road.)

The BufferedReader "Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines." I use it because the readLine() method makes it really easy to deal with the input as a String. If I didn't wrap it around the InputStreamReader, I'd have to use the InputStreamReader's read() method, which returns one character at a time.


thanks... i really learnt from it

its a nice way to explain .. n seems much simpler !!


Why are you not using a Scanner object?

Scanner input = new Scanner( );

Thanks for the tip. To answer your question, this article was written before Java 5 and the Scanner class came around.

Here's an updated version of this class, demonstrating how to read command line input from a Java program using the Scanner class:

import java.util.Scanner;

public class ScannerTest

  public static void main (String[] args)
    //  prompt the user to enter their name
    System.out.print("Enter your name: ");

    // get their input
    Scanner scanner = new Scanner(;

    // there are several ways to get the input, this is 
    // just one approach
    String username = scanner.nextLine();

    // test the String
    if (username.trim().equals(""))
      System.out.println("Hmm, I didn't get your name");
      System.out.println("Thanks for the name, " + username);


As mentioned, there are several ways to get input from the Scanner class, and I recommend taking a look at the Scanner class javadoc.


This are nice snippets ...
I was able to plug-in your "input reader" snippet in to the "system exec" program and was able to interactively execute any system calls!!!
Like if I want to do a bioinformatics blast search I just have to pass the required parameters and it does the job:EG:

[feseha@voyager Jfiles]$ java JavaRunCommand2
Enter your command: bl2seq -i test1.fna -j test2.fna -p blastn

Ans it works like a charm ...

Cool stuff!
Thank you


Very good. You have shown me classic and new way to read input at command prompt from user. I want you explain more about Scanner class methods for primitive read operation.


Hello i am a very beginner in Java, if i willing to use this code in netbean, what module should i install? Before this i compile this coding on bluej but noting happen.. sorry asking this question but i am really want to know how to use it.

Here's a corrected version of your code:


public class BRRead
  public static void main( String args []) throws IOException
    BufferedReader br = new BufferedReader(new InputStreamReader(;
    System.out.println("Enter character, 'q' to quit");

    char c;
    while ( (c = (char) != 'q')
      System.out.println("char: " + c + ".");

You were very close, except for a few typos.

Also, sorry, I don't use NetBeans, and I don't know how to make this work from there. I just run it from the command line (Unix command line, in my case).

I hope that is helpful, and thanks for the nice "while loop" example of this code.


I'm sorry, I don't use NetBeans, and so I can't be much help here, but I thought I'd post your comment here in case someone else can answer it.


I´m beggining with java and started making a simple program which counts the digits of the number entered by the user. This is where it all stops working, I tried using the Scanner, but apparently it can be used with string only.

Can anyone help?

import java.util.Scanner;

class NrDigits3 {
public static void main (String[] args) {

int d=1;
System.out.println ("Write the number of which you want to count the digits");

Scanner scanner = new Scanner(;
int n = scanner.nextLine();

if (n<10)
{ System.out.println(d);}

while (n>= 10)
if (n<10)



I would like to know how to mask a password entered using command line.

I had gone through the code given by SUN microsystems for masking a password. But that thread runs into an infinite loop and it seems it has a bug.

I'm using Java 1.5.

Could you guys help me out...



What can be done for passwords. I would like to get input but I do not want it to be shown on the screen while it is being typed. How can I accomplish that?

Masking passwords on the command line with Java is tricky business. If you know you're on a Unix system, you might be able to print something from your Java program to tell the terminal not to display the input the user types, and then set it back to normal when you're done. I haven't done this in a long time, but you can do it with the Unix stty command, or even with a simple echo statement.

A second approach is to have your Java program run a separate thread that masks the password as the user types it, essentially deleting each character after the user types it. This is shown in this Sun/Oracle password masking tip.

I would imagine that you've figured this out by now, but just in case:

You've got your int set up right now to take a string by using the .nextLine() function of the Scanner class. What you want is the .nextInt(); function. That should clear up the issue for you.


We have such command line (Monica 29 Dan 35 Michale 16)
I must to count the average of this numbers and to show these names with their ages.

Can you help me? Should I make an array firstly?



Thanks for your post dude, its really useful for replacing DataInputStream readLine() method which is deprecated.