The byte code ranges from 0 to 256 (and -1 which indicates the EOF), but the java byte variable ranges from -128 to 128. How is that method able to store the bytes from the code into byte variables?
Asked
Active
Viewed 677 times
1 Answers
3
I'm not sure what you're unclear about:
is.read(byte[])
reads an array of 8-bit values. The fact that those values are signed (-128..127, not "128")) is irrelevant.- It doesn't need to store an out of band value like EOF. It simply stops reading at EOF. The array's
.length
is the buffer size and/or the #/bytes successfully read before EOF.
PS: It's common practice to query the filesize and allocate the byte array before calling read().

paulsm4
- 114,292
- 17
- 138
- 190
-
What I'm unclear about is how this method is able to store the data into byte arrays. From what I have read, every read() method returns a int variable, since the byte variable in java is too small to store the actual bytes from the byte code (because they range from 0 to 256). Yet there is a method(read(byte[])) which stores byte code into array of byte variables. What is confusing me is how is that possible? – FlickIt Dec 07 '20 at 22:21
-
2@FlickIt `read()` returns an `int` so it can returned the _unsigned_ "byte" value _as well as_ `-1` to indicate EOF. Also, an `int` in the range `0-255` can be converted into a `byte` without loss of data (it will just now be in the range `-128-127`). – Slaw Dec 07 '20 at 22:26
-
1@FlickIt For example, `int i = 255; byte b = (byte) i` will give you `b == -1`. – Slaw Dec 07 '20 at 22:30
-
Here's the Javadoc for `inputStream.read()`: https://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html: 1) It returns the #/bytes read for this particular "read()". It's NOT one of the data values, it's the #/values read. That number will always be less than or equal to the length of the byte array (or "-1", for end-of-stream). 2) The byte array itself contains ... an array of bytes :) A "byte" is simply "8 bits". In C, a byte is an integer that can either be signed or unsigned. In Java, a byte is always signed. Q: Does that make sense? What are you still unclear about? – paulsm4 Dec 07 '20 at 22:34
-
See also this thread: https://stackoverflow.com/questions/7401550/ – paulsm4 Dec 07 '20 at 23:00
-
I think everyting is clear now. The read() methods return a int value because of the -1 EOF value which has to be returned, and since in java a byte variable is always signed -1 is still a valid number (-128 to 127, while with int representing it it's from 0-255 and -1 for the EOF). Also the read(byte[]) method simply stores the read value in signed format in the byte array(-128 to 127) . – FlickIt Dec 08 '20 at 10:26