Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do "call by reference" in Java?

  1. How to do "call by reference" in Java? (Assume that we are using that term in the same way that it has been used in peer-reviewed CS literature since the 1960's; see this Wikipedia page for a simple explanation.)

  2. Since Java doesn't support pointers, how is it possible to call a function by reference in Java like we do in C and C++??

like image 344
Shashi Bhushan Avatar asked May 17 '11 09:05

Shashi Bhushan


People also ask

Can you do call by reference in java?

You cannot do call by reference in Java. Period. Nothing even comes close. And passing a reference by value is NOT the same as call by reference.

What is call by reference with example?

The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. It means the changes made to the parameter affect the passed argument.


1 Answers

Real pass-by-reference is impossible in Java. Java passes everything by value, including references. But you can simulate it with container Objects.

Use any of these as a method parameter:

  • an array
  • a Collection
  • an AtomicXYZ class

And if you change its contents in a method, the changed contents will be available to the calling context.


Oops, you apparently mean calling a method by reference. This is also not possible in Java, as methods are no first-level citizens in Java. This may change in JDK 8, but for the time being, you will have to use interfaces to work around this limitation.

public interface Foo{     void doSomeThing(); }  public class SomeFoo implements Foo{     public void doSomeThing(){        System.out.println("foo");     } }  public class OtherFoo implements Foo{     public void doSomeThing(){        System.out.println("bar");     } } 

Use Foo in your code, so you can easily substitute SomeFoo with OtherFoo.

like image 183
Sean Patrick Floyd Avatar answered Oct 06 '22 00:10

Sean Patrick Floyd