Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does System.in.read actually return?

Tags:

java

java-io

What does :

System.in.read()

return ? The documentation says :

Returns: the next byte of data, or -1 if the end of the stream is reached.

But for example if I enter : 10 I get back 49 . Why is that ?

like image 929
saplingPro Avatar asked Mar 07 '13 14:03

saplingPro


People also ask

What does system in read do?

System indicates the current computer system. System. in. read indicates reading from a standard input device.

How does system in work?

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.


1 Answers

49 is the ASCII value of the char 1. It is the value of the first byte.

The stream of bytes that is produced when you enter 10Enter on your console or terminal contains the three bytes {49,48,10} (on my Mac, may end with 10,12 or 12 instead of 10, depending on your System).

So the output of the simple snippet

int b = System.in.read();
while (b != -1) {
    System.out.println(b);
    b = System.in.read();
}

after entering a 10 and hitting enter, is (on my machine)

49
48
10
like image 168
Andreas Dolk Avatar answered Sep 16 '22 22:09

Andreas Dolk