2

I am recently wondering how functions like the InputStream int read(byte[] b) method are working. I know that Java is always passing method parameters by value, and not by reference.

Knowing this, I don't understand how an empty byte-array can contain values after passing it to the read-method (assuming there were bytes to read in the InputStream). From all I know, only the value passed to the read-method will be touched internally and the only output should be the number of read bytes (the integer return value). But still the byte-array somehow fills.

How is this actually done?

1
  • The reference is passed by value, but it's still a reference to the original byte array, so it can be used to fill it. Commented Mar 26, 2015 at 6:55

2 Answers 2

2

The reference to the byte[] is passed as value. Pass by reference would mean that the address to the variable holding the reference to the byte[] was passed.

Sign up to request clarification or add additional context in comments.

Comments

0

Objects like arrays are passed by reference. You can think of it as the object variable being a pointer and that pointer being passed by value, which amounts to the same thing. It's only primatives like ints and floats that are really passed by value.

8 Comments

Are the primitive types the only exception that are actually passed by value?
@Chirs yes. Though note that for immutable objects like Strings, pass by reference and value are almost equivalent.
Nope. The reference is passed by value, and this is different from pass by reference and from pass by value.
@Louis What's the difference? I don't think there is any difference at the abstraction level of Java.
@Antimony: stackoverflow.com/questions/40480/… explains some of the details, but pass by reference supports swapping and Java does not. The distinction is important.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.