I've done a lot of research but only found that java cannot pass object by reference. But, then how does System.arraycopy()
change the value of an array provided.
Asked
Active
Viewed 745 times
1

Ritik Jain
- 21
- 1
-
1You can't pass objects *at all*, actually. – user253751 Feb 25 '15 at 09:22
-
3Have a look at [http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value](http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value). – BluesSolo Feb 25 '15 at 09:26
-
What do you think happens when you read all of the data of an array and put it in a newly created array? – Ceiling Gecko Feb 25 '15 at 09:26
-
Java only allow passing objects as a reference. The confusion point is that references are passed by value. – Peter Lawrey Feb 25 '15 at 09:28
3 Answers
0
System.arraycopy()
changes an array's contents, not the object/reference itself. The array you include as input parameter must be declared outside the method.

Ray
- 3,084
- 2
- 19
- 27
0
I do not know exactly what your "pass object" means. If you means call a function and pass object as parameter. Then in Java, any Object is passed in reference. This means that if you modify that object in the function called, the modification will take effect even function returns.

zchen
- 109
- 2
- 7
-
2Actually, in Java everything *is pass by value*.. even references are passed by value.. – TheLostMind Feb 25 '15 at 09:32
0
System.arraycopy()
changes contents of an array, not the exact array. However it's possible to write a Pointer
class.
public class Pointer<T>{
private T value;
public Pointer(T value){
this.value = value;
}
public T get(){
return value;
}
public void set(T value){
this.value = value;
}
}
Pointer<SomeClass> pointer = new Pointer<>(theObject);
pointer.set(otherObject);
theObject = pointer.get();
Or to use "the System.arraycopy()
trick":
SomeClass[] pointer = new SomeClass[]{ theObject };
pointer[0] = otherObject;
theObject = pointer[0];

Kamil Jarosz
- 2,168
- 2
- 19
- 30