0

I need to pass a byte[] in a Java method, and inside the method i need to "change" the byte[], but i don`t want to change the local byte[], i want to change the passed byte[] to the method, like a pointer, for example.

byte[] arr = new byte[10];
doSomethingWithByteArr(arr);
// And now, arr would have changed...
Lukas Knuth
  • 25,449
  • 15
  • 83
  • 111
Ivan Seidel
  • 2,394
  • 5
  • 32
  • 49
  • 4
    If you modify the array in the function, those changes will be reflected in the caller's view. Only a copy of the reference to the array is given to the caller, not a copy of the array itself. – sjr Jun 13 '12 at 23:12
  • There are no pointers in java like you know them from C/C++ You should read this question for more details: http://stackoverflow.com/questions/40480/is-java-pass-by-reference – Lukas Knuth Jun 13 '12 at 23:16
  • Although you can't, for instance, modify the length of the array. – Neil Jun 13 '12 at 23:23

3 Answers3

1

Java is pass-by-reference-value when passing non-primitive arguments to methods, and is pass-by-value when passing primitives, meaning that if you have a byte array and you pass it to a modification method, that object will be modified.

Example:

public static void main(String[] args) {
    byte[] arr = new byte[10];
    for (int i = 0; i < arr.length; i++) {
        arr[i] = i;
    }
    // arr now contains { 0, 1, 2, 3, ... 9 }
    System.out.println(Arrays.toString(arr));
    randomize(arr);
    // arr now contains (ex.) { 6, 3, 7, 1, 9, 3, 2, 6, 3, 0 }
    System.out.println(Arrays.toString(arr));
}

public void randomize(byte[] arr) {
    Random random = new Random();
    for (int i = 0; i < arr.length; i++) {
        arr[i] = random.nextInt(10);
    }
}
FThompson
  • 28,352
  • 13
  • 60
  • 93
0

In Java only primitive types are copied when passed to a function. That pseudocode should work as you expect.

Although in Java everything is passed by copy, non primitive types are actually references, that's why your byte[] refers to the same instance inside and outside the function.

Butaca
  • 416
  • 4
  • 14
0

Not sure if i understand your dilemma.

Java passes its parameters by value every time. This meaning if its a primitive it passes the value of it, and if its an object or array, it passes the value of the object referenced by it.

So if you pass an array you can modify it and since its an alias it will be reflected on the array outside of the method. But you wont be able to point the arr variable to a new reference from within the method code, you could return a new byte[] and assigning to it if you want to change it.

To my knowledge, Java doesn't support passing parameters by reference.

Ed Morales
  • 1,027
  • 5
  • 9