0

In the program I am writing for homework I have a FileInputStream which I am reading bytes from into an array using the read() 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
    System.out.println(bytes[0]);


}catch(IOException e)
{
    e.printStackTrace();
}
Cody
  • 484
  • 6
  • 20
giraffesyo
  • 4,860
  • 1
  • 29
  • 39
  • Call by value doesn't mean that an object can't be mutated. [This answer](http://stackoverflow.com/a/40523/3824919) explains that. – Tom Nov 20 '16 at 02:53
  • 1
    The variable bytes is actually a reference to the array object. When you pass array to a method you are copying the reference not the actual array the the reference refers. – Ganesh S Nov 20 '16 at 02:55

1 Answers1

1

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)

Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79