What does System.in.read actually return?

11,678

Solution 1

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

Solution 2

System.in.read() reads just one byte.

49 is the Unicode point value for 1.

Try to print:

System.out.println((char)49);

This will help you to understand it more.

Solution 3

When you enter 10, it is not read as an integer but as a String or, more precisely here, an array of bytes.

49 is the ASCII code for the character 1.

Share:
11,678
saplingPro
Author by

saplingPro

I love to write code and love to be known as a programmer. I try very hard to be creative. I am a hard working man ! I don't know where i am heading and don't know where i will be :(

Updated on June 13, 2022

Comments

  • saplingPro
    saplingPro almost 2 years

    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 ?

  • Stephen C
    Stephen C about 11 years
    Because 10 is two bytes. A byte representing the character 1, followed by a byte representing the character 0.
  • yshavit
    yshavit about 11 years
    @saplingPro The thing to realize is that when you enter "10", you're not entering the number 10, but rather text which happens to be "10" but could have been "foo" or even "☃ is melting!". What System.in sees are the bytes of this text stream. For ascii and extended ascii (so, not my little snowman up there), check out ascii-code.com