Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to pass byte[] by reference?

Tags:

You can do it in .NET by using the keyword "ref". Is there any way to do so in Java?

like image 218
Mahendra Avatar asked Dec 02 '08 05:12

Mahendra


People also ask

What is byte [] in Java?

A byte in Java is 8 bits. It is a primitive data type, meaning it comes packaged with Java. Bytes can hold values from -128 to 127. No special tasks are needed to use it; simply declare a byte variable and you are off to the races.

Can you pass an array by reference in Java?

Does Java pass Array by Reference to a Method? Yes, and that is the only way to pass an array to a function in Java. In Java, a function is called a method, and it is a member of a class.


1 Answers

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.)

like image 54
Jon Skeet Avatar answered Oct 05 '22 02:10

Jon Skeet