I am having a problem to understand what System.in do. All I understand is that it's a data field in the System class and that it's declaration is:
public static final InputStream in
It's declared final so it cannot be changed.
As mentioned in the Oracle source they say that "in" is the "standard" input stream. This stream is already open and ready to supply input data. Typically this stream corresponds to keyboard input or another input source specified by the host environment or user.
What does this exactly mean?
When I write the following code :
Scanner input = new Scanner(System.in);
That Scanner object is ready to scan what's in System.in, but nothing shows up in the CMD.
Another point is that when I try to print System.in, I end up with an output like:
java.io.BufferedInputStream@15db9742
Can anyone please explain the whole process and what's the exact job of both System.in and Scanner class!
System.in
is a BufferedInputStream
, such a Stream
can be any input stream (for instance a network socket, or a file), but also the standard input channel stdin
.
stdin
is the content you type in the command line, so obviously, it doesn't show anything.
When you create a Scanner
as shown in your question, you feed the standard input channel to that Scanner
, but the scanner won't do anything until it is asked to. A scanner is a wrapper: a construct that makes it easier (more convenient) to parse input from the stdin
. It does not offer additional functionality in the sense you can do all what a scanner does by yourself, but it is way easier to use a scanner if you want to parse for instance integers from the stdin
.
So when you for instance type:
Scanner sc = new Scanner(System.in);
int val = sc.nextInt();
System.out.println(2*val);
It will wait until you input a line, parse it to an integer and print the double of the inputted value on the standard output channel (stdout
).
A few concluding notes:
System.in
is notfinal
, you can useSystem.setIn
to set another input stream as the standard input string. For instance a file or a network socket. The defaultSystem.in
can also take input from for instance a file or a pipe if you for instance call the program asjava -jar program.jar < inputfile
.