Question

I read some code here: Is Java "pass-by-reference" or "pass-by-value"?

public void foo(Dog d)
{
  d.getName().equals("Max"); // true
  d.setName("Fifi");
}

Dog aDog = new Dog("Max");
foo(aDog);
aDog.getName().equals("Fifi"); // true

Can I perform the same with the Byte object. I am at this point in my code and wondering how to "set" the value of the byte object?

If i use the = assignment operator it seems to perform the new Byte() autoboxing?! and therefore the value is not passed back.

Any ideas? Regards.

Was it helpful?

Solution

Byte is immutable, which means its value cannot be changed. Assigning to it won't work in your case, since that would simply rebind the reference (which won't propagate back to the caller).

You could use MutableByte, a one-element byte/Byte array, or a custom class.

OTHER TIPS

The previous answer is correct, but just to add - yes in this case the Byte object is passed by reference. However because the Byte object is immutable even though it is passed by reference there is no way to modify it.

To be more specific when you call a function the parameters into the function are passed by value, but when you pass an Object what you actually pass by value is a reference to that object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top