Recently
while writing some java program. I wanted to quickly run some test cases using
runtime inputs from console. I am working on some of the legacy system which
runs on java1.5 and recently has been upgraded to java1.6 version.
For
taking user input during run time, I have always used Scanner API. But recently
came to know about Console class. Though it was included as part of Java1.6 release.
But I never used it any time. Just wanted to share some information on the available
API which is used for user input:
-Scanner
(Included in Java1.5)
-BufferedReader
(Included in Java1.1)
-Console
(Included in Java1.6)
From
developers point, I assume following factors could be considered during the
selection of any of the above APIs:
If
your input size is more, or more number of inputs is going to be used in
the program, it is advisable to use BufferedReader instead of Scanner. It will
be difficult to observe the speed for fewer inputs. But for huge data (for
millions of inputs), definitely there will be an edge in using BufferedReader.
Scanner could read anything, for example lines, whitespace as tokens,
any other regular expression tokens, characters or numbers.
While there is limitation in reading regex for BufferedReader and Console. They
could read characters, arrays etc. BufferedReader and Console does
not facilitate any kind of parsing unless it is handled explicitly. The
Exception handling works differently for each of these. Scanner and Console do
not throw Checked exception where as BufferedReader complains for Checked Exception.
Scanner isn’t synchronized, BufferedReader synchronized.
These
are the few points that could be helpful in understanding the mechanism of
taking input from user in Java.
Feel
free to add any more points.
Comments
Post a Comment