Java 5 introduced a nice utility called java.util.Scanner which is capable of reading input form command line in Java. Using Scanner is a nice and clean way of retrieving user input from console or command line. The scanner can accept InputStream, Reader or simply path of the file from where to read input. In order to read from the command line, we can pass System.in into Scanner's constructor as a source of input. The scanner offers several benefit over classical BufferedReader approach, here are some of the benefits of using java.util.Scanner for reading input from command line in Java:
1) The scanner supports regular expression, which gives you the power to read only matching the pattern from the input.
2) The scanner has methods like nextInt(), nextFloat() which can be used to read numeric input from command line and can be directly used in code without using Integer.parseInt() or any other parsing logic to convert String to Integer or String to double for floating point input.
Reading input from the command line should be the first few thing which new Java programmer should be taught as it helps them to write an interactive program and complete programming exercise like checking for a prime number, finding the factorial of a number, reversing String etc. Once you are comfortable reading input from the command line you can write many interactive Java application without learning in GUI technology like Swing or AWT.
Java program to read input from command prompts in Java
Here is sample code example of How to read input from the command line or command prompt in Java using java.util.Scanner class:
Just note that java.util.Scanner nextInt() will throw "Exception in thread "main" java.util.InputMismatchException" exception if you entered String or character data which is not number while reading input using nextInt(). That’s all on how to read user input from the command line or command prompt in Java.
Related Java programming tutorials for beginners