Michael McQuade Michael McQuade - 9 months ago 45
Java Question

How can FileInputStream.read change my byte array?

In the program I am writing for homework I have a

which I am reading bytes from into an array using the
method of the stream. I am not using the return value at all in my program, as I'm not interested in it.

However, I'm wondering how is it actually modifying my array? I read through many stackoverflow posts lasts night that indicated that Java is pass by value, not by reference, and I even proved it myself with a simple program.

How does this method modify my byte array?

try {
input = new FileInputStream(FileName);
bytes = new byte[input.available()];
input.read(bytes); // reads file in as bytes and stores into bytes

}catch(IOException e)

Answer Source

Java passes the reference to the byte array to the read method by value. This means that the read method cannot make your local variable bytes point to a different byte array, but it can change the contents of the byte array that you passed into it.

(If Java were "pass by reference", then a method could make your local variable point to a different object - which is not possible in Java)