Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does System.in() work?

Tags:

java

I have written a code to accept a char and a string:

    public static void main(String[] args) throws IOException {
    System.out.println("enter one char");
    char c = (char) System.in.read();
    System.out.println("The char entered is :" + c);
    String userInput;
    System.out.println("Enter a string");
    Scanner s = new Scanner(System.in);
    userInput = s.next();
    System.out.println("the string inputted is:" + userInput);}

output:

enter one char
asdfg
The char entered is :a
Enter a string
the string inputted is:sdfg

Can anyone explain why is it so?

like image 648
Rupali Avatar asked Dec 29 '25 05:12

Rupali


2 Answers

As Tim Biegeleisen stated, System.in() returns an InputStream. Scanner can also operate on an InputStream. InputStream's read() method consumes the first byte in the stream, which you cast to a char (which works because it takes a byte to store a char so you can cast between the types with no truncation).

Let's break it down.

System.in() https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#in

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.

InputStream's read() https://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html#read--

Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255...

Scanner https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

Scanner's next() https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#next--

Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern...

System.in().read() will read/consume the first byte off the a static InputStream. Instantiating a new Scanner from the same InputStream then calling next() consumes the remaining token.

I encourage you to explore the Java API Documentation for any classes or methods you have trouble understanding. Break things down into individual types and examine their constructor and method descriptions.

like image 143
Justin Reeves Avatar answered Dec 30 '25 22:12

Justin Reeves


System.in: An InputStream which is typically connected to keyboard input of console programs. It is nothing but an in stream of OS linked to System class. Using System class, we can divert the in stream going from Keyboard to CPU into our program. This is how keyboard reading is achieved in Java.

like image 34
dhS Avatar answered Dec 30 '25 22:12

dhS