I have a question regarding the concept of Java using pass-by-value. I do a lot of programming in C but I am very inexperienced with Java so I have been writing some code to learn a bit more about it. I have read many stack-overflow questions regarding whether there is ever any pass-by-reference, the answer seems to be that Java always uses pass-by-value (with the slight deviation being it passes references to objects by value).
With this in mind I’ve managed to properly confuse myself, I don’t understand how the following example can be an instance of pass-by-value. I would appreciate an explanation as to the internal Java workings that I don’t understand.
I have the following code:
byte[] myByteArray = {23, 45, 67};
myHashMap.put(myKey, new TestClass(100, myByteArray, myOtherByteArray));
Arrays.fill(myByteArray, (byte)0);
Where myHashMap
is a ConcurrentHashMap
and TestClass
is defined:
public class TestClass
{
public final int number;
public final byte[] byte1;
public final byte[] byte2;
public TestClass(int a, byte[] b, byte[] c)
{
number = a;
byte1 = b;
byte2 = c;
}
}
When I use the debugger to step through the code I can see that the byte1
variable stored in TestClass
(And subsequently in the ConcurrentHashMap
) is altered by the Arrays.fill
call, my question is ... why?
When instantiating a new TestClass
am I not passing myByteArray
by value?