I guess java does not have the option \"pass by reference\" .But why ? Because sometimes it is very needed.
I guess the only place you really need pass by reference is to return multiple values from a function like the out
keyword in C. To do this in Java, you can either create a class to hold the objects or use an existing Pair class offered by many libraries.
Similarly, you can pass a stub object that refers to something else and then you can change the reference in the object and see it reflected externally:
public static class Holder<T> {
public T value;
public Holder(T value) {
this.value = value;
}
}
private Holder<Object> itsValueCanBeSeenAsPassedByReferencce
= new Holder<Object>("a");
public void doSomething(Holder<Object> holder) {
holder.value = "b";
}
In Java no matter what type of argument you pass the corresponding parameter (primitive variable or object reference) will get a copy of that data, which is exactly how pass-by-value (i.e. copy-by-value) works. In Java, if a calling method passes a reference of an object as an argument to the called method then the passed in reference gets copied first and then passed to the called method. Both the original reference that was passed-in and the copied reference will be pointing to the same object. So no matter which reference you use, you will be always modifying the same original object, which is how the pass-by-reference works as well.
Any time you feel the need to pass a value by reference, instead pass a reference by value. While Java does not have a "pass by reference" mechanism, it does have references. So just pass those references by value.