Java 5 introduced a nice utility called java.util.Scanner which is capable to read input form command line in Java. Using Scanner is nice and clean way of retrieving user input from console or command line. Scanner can accept InputStream, Reader or simply path of file from where to read input. In order to reading from command line we can pass System.in into Scanner's constructor as source of input. Scanner offers several benefit over classical BufferedReader approach, here are some of benefits of using java.util.Scanner for reading input from command line in Java:
1) Scanner supports regular expression, which gives you power to read only matching pattern from input.
2) 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 command line should be the first few thing which new Java programmer should be taught as it help them to write interactive program and complete programming exercise like checking for prime number, finding factorial of number, reversing String etc. Once you are comfortable reading input from 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 prompt in Java
Here is sample code example of How to read input from 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 command line or command prompt in Java.
Related Java programming tutorials for beginners