Java: How to pass byte[] by reference?

What are you doing in your method? If you’re merely populating an existing array, then you don’t need pass-by-reference semantics – either in .NET or in Java. In both cases, the reference will be passed by value – so changes to the object will be visible by the caller. That’s like telling someone the address of your house and asking them to deliver something to it – no problem.

If you really want pass-by-reference semantics, i.e. the caller will see any changes made to the parameter itself, e.g. setting it to null or a reference to a different byte array, then either method needs to return the new value, or you need to pass a reference to some sort of “holder” which contains a reference to the byte array, and which can have the (possibly changed) reference grabbed from it later.

In other words, if your method looks likes this:

public void doSomething(byte[] data)
{
    for (int i=0; i < data.length; i++)
    {
        data[i] = (byte) i;
    }
}

then you’re fine. If your method looks like this:

public void createArray(byte[] data, int length)
{
    // Eek! Change to parameter won't get seen by caller
    data = new byte[length]; 
    for (int i=0; i < data.length; i++)
    {
        data[i] = (byte) i;
    }
}

then you need to change it to either:

public byte[] createArray(int length)
{
    byte[] data = new byte[length]; 
    for (int i=0; i < data.length; i++)
    {
        data[i] = (byte) i;
    }
    return data;
}

or:

public class Holder<T>
{
    public T value; // Use a property in real code!
}

public void createArray(Holder<byte[]> holder, int length)
{
    holder.value = new byte[length]; 
    for (int i=0; i < length; i++)
    {
        holder.value[i] = (byte) i;
    }
}

For more details, read Parameter passing in C# and Parameter passing in Java. (The former is better written than the latter, I’m afraid. One day I’ll get round to doing an update.)

Leave a Comment

tech