How to read from command line in Java

Reading from command line to get User input is a common task. Let’s see how to do it in Java

Java provides java.util.Scanner class to help read from Console. Let’s see the code that shall take name and age as input and print it back.

package com.codezuzu;

import java.util.Scanner;

public class ConsoleReader {

  public static void main(String[] args) {
    Scanner scanner = new Scanner(;
    System.out.println("Please enter your Name:");
    String name = scanner.nextLine();
    System.out.println("Please enter your age:");
    int age = scanner.nextInt();
    System.out.println(String.format("%s your age is %d", name, age));


We initialize Scanner with to set command line as source of input. Scanner can also get input from file.
Scanner provides various API’s to get the data in desired data types. We use nextLine() to get the name and nextInt() to get the age. Once we run, here it how the output looks

Please enter your Name:
Please enter your age:
codezuzu your age is 1

What if we add invalid age?

If we enter invalid input, it shall throw an exception providing an ability to handle it.

Please enter your Name:
Please enter your age:
Exception in thread "main" java.util.InputMismatchException
	at java.util.Scanner.throwFor(
	at java.util.Scanner.nextInt(
	at java.util.Scanner.nextInt(
	at com.codezuzu.ConsoleReader.main(
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(
	at java.lang.reflect.Method.invoke(
	at com.intellij.rt.execution.application.AppMain.main(

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.