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.

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

What if we add invalid age?

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

Leave a Reply

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