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

- 698,415
- 94
- 811
- 1,216

- 1,481
- 3
- 16
- 20
-
2Judging from the answers so far, I guess the question is ambiguous. Can you provide an example in C or C++ of what you are trying to achieve? – Björn Pollex May 17 '11 at 09:48
-
Take the example of swapping of two numbers....as given by Stephen C....Is it possible in Java??? – Shashi Bhushan May 17 '11 at 10:51
-
1see this previous answer of mine: http://stackoverflow.com/questions/3624525/how-to-write-a-basic-swap-function-in-java/3624554#3624554 – Sean Patrick Floyd May 17 '11 at 10:59
-
I have attempted to resolve the ambiguity by making the question about BOTH classical pass-by-reference AND passing function pointers (which is *actually* passing references by value). – Stephen C Jul 18 '21 at 06:17
12 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
.

- 292,901
- 67
- 465
- 588
-
2I think you mean pass-by-reference. I think the OP is asking about call-a-method-using-a-reference-to-the-method. ;) – Peter Lawrey May 17 '11 at 09:46
-
1+1 for a thorough answer that covers all possible meanings of the OP's question! – Oliver Charlesworth May 17 '11 at 09:58
How to 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.
(Real "call by reference" allows you to do this kind of thing:
void swap(ref int i, ref int j) { int tmp = *i; *i = *j; *j = tmp }
int a = 1;
int b = 2;
swap(a, b);
print("a is %s, b is %s\n", a, b); // -> "a = 2, b = 1"
You simply can't do that in Java.)
Since Java doesn't support pointers ...
While this is technically true, it would not be an impediment to what you are trying to do.
Java does support references, which are like pointers in the most important respects. The difference is that you can't treat references as memory addresses by doing arithmetic on them, converting them to and from integer types and so on. And you can't create a reference to a variable because the concept does not exist in Java or the JVM architecture.
How is it possible to call a function by reference in Java like we do in C and C++??
Important note: this is NOT "call by reference". It is "call by value" using a reference to a function1.
Prior to Java 8, references to functions were not supported as values. So you could not pass them as arguments, and you cannot assign them to variables.
However, you can define a class with one instance method, and use an instance of the class instead of a function reference. Other Answers give examples of this approach.
From Java 8 onwards, method references are supported using ::
syntax. There are 4 kinds of method reference:
- Reference to a static method:
ContainingClass::staticMethodName
- Reference to an instance method of a particular object:
containingObject::instanceMethodName
- Reference to an instance method of an arbitrary object of a particular type:
ContainingType::methodName
- Reference to a constructor:
ClassName::new
1 - From a pedagogical perspective, it is unfortunate that C and C++ use the &
symbol for both call-by-reference and for denoting function pointers. However, from a language design perspective, I don't disagree with that design choice.

- 698,415
- 94
- 811
- 1,216
-
2Some might also find this blog post useful: http://javadude.com/articles/passbyvalue.htm – Sandman Jul 12 '11 at 12:37
Usually in java this is solved by using interfaces:
Collections.sort(list, new Comparator() {
@Override
public int compareTo(Object o1, Object o2) {
/// code
}
});

- 42,730
- 18
- 77
- 103
-
The only reason you can modify `list`, is through `list`'s methods. If the parameters were `int`s, interfaces don't help. The OP is referring to being able to modify the actual parameter through the formal parameter. – jbruni Jan 05 '17 at 16:34
package jgf;
public class TestJavaParams {
public static void main(String[] args) {
int[] counter1 = new int[1];
counter1[0] = 0;
System.out.println(counter1[0]);
doAdd1(counter1);
System.out.println(counter1[0]);
int counter2 = 0;
System.out.println(counter2);
doAdd2(counter2);
System.out.println(counter2);
}
public static void doAdd1(int[] counter1) {
counter1[0] += 1;
}
public static void doAdd2(int counter2) {
counter2 += 1;
}
}
Output would be:
0
1
0
0

- 179
- 1
- 6

- 8,425
- 4
- 58
- 92
Java allows only call by value. However, references to objects can be transferred to the called function using call by value. These references if used to manipulate the data of the object in the called function, this change will be visible in the calling function also. We can not do pointer arithmetic on the references as we do with pointers but references can point to the data of the object using period operator which functions as '*' operator in C/C++.

- 11
- 1
JAVA does allow internal reference using objects. When one write this assignment Obj o1 = new Obj(); Obj o2=o1; What does it do, that both o1 and o2 points to the same address. Manipulating any object's space, will reflect in the other's also.
So to do this, as mentioned above you can either use Array, Collections

- 402
- 5
- 10
The best way is to use an interface which performs the action.
// Pass a Runnable which calls the task() method
executor.submit(new Runnable() {
public void run() {
task();
}
});
public void task() { }
You can use reflections to call any method
Method method = MyClass.class.getMethod("methodToCall", ParameterType.class);
result = method.invoke(object, args);

- 525,659
- 79
- 751
- 1,130
In Java, except for primitives, passing Object to a method/function is always by reference. See Oli Charlesworth's answer for the example.
For primitive types, you can wrap it using array: For example:
public void foo(int[] in){
in[0] = 2;
}
int[] byRef = new int[1];
byRef[0] = 1;
foo(byRef);
// ==> byRef[0] == 2.
-
Wrapping primitive type in an array does work. See code with package jgf: – JGFMK Sep 11 '13 at 16:56
-
2A lot of ppl confuse between "call by reference" and "object references are passed by value". In Java, it is always "call by value". – jAckOdE Dec 27 '13 at 16:38
http://www.javaworld.com/javaqa/2000-05/03-qa-0526-pass.html
Java does manipulate objects by reference, and all object variables are references. However, Java doesn't pass method arguments by reference; it passes them by value.

- 13
- 1
- 6
-
2While true, it's important to note one very important thing: The *value* being passed is *the object's reference*. – Andrew Barber Sep 10 '12 at 13:45
From Java The Complete Reference by Herbert Shildt 9th edition: "When you pass an object to a method, the situation changes dramatically, because objects are passed by what is effectively call-by-reference. Keep in mind that when you create a variable of a class type, you are only creating a reference to an object. Thus, when you pass this reference to a method, the parameter that receives it will refer to the same object as that referred to by theargument. This effectively means that objects act as if they are passed to methods by use of call-by-referen ce. Changes to the object inside the method do affect the object used as an argument."
package objectpassing;
public class PassObjectTest {
public static void main(String[] args) {
Obj1 o1 = new Obj1(9);
System.out.println(o1.getA());
o1.setA(3);
System.out.println(o1.getA());
System.out.println(sendObj1(o1).getA());
System.out.println(o1.getA());
}
public static Obj1 sendObj1(Obj1 o)
{
o.setA(2);
return o;
}
}
class Obj1
{
private int a;
Obj1(int num)
{
a=num;
}
void setA(int setnum)
{
a=setnum;
}
int getA()
{
return a;
}
}
OP: 9 3 2 2
FInal call to getA() shows original object field 'a' was changed in the call to method public static Obj1 sendObj1(Obj1 o).

- 65
- 8
-
I now own about 5 books on Java. Put bluntly, most of the authors SUCK at writing books and their mastery of the Java language is questionable at best. – Dave Black Aug 20 '14 at 11:35
-
The author who wrote that quoted text does not understand what "call by reference" really means. Call by reference means passing a reference **to a variable**. Saying that passing a reference to a variable and a reference to an object are "effectively the same thing" is like saying that cars and bicycles are effectively the same thing. – Stephen C Jul 18 '21 at 05:54
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.
I used an array to do this...
package method;
import java.util.Scanner;
public class InterChange {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int a[]=new int[2];
System.out.println("Enter two values");
for(int i=0;i<2;i++) {
a[i]=sc.nextInt();
}
hange(a);
for(int i=0;i<2;i++) {
System.out.println(a[i]);
}
}
static int hange(int b[])
{
int temp;
temp=b[0];
b[0]=b[1];
b[1]=temp;
return b[0]&b[1];
}
}
Yes, you can implement Call by Reference in another way by "Pass by Reference".
- You should pass the reference object of a class created.
- Then you can manipulate the object's data by member function (.), which will be reflected in original data.
In below code the original data --> x is manipulated by passing the reference object.
public class Method_Call {
static int x=50;
public void change(Method_Call obj) {
obj.x = 100;
}
public static void main(String[] args) {
Method_Call obj = new Method_Call();
System.out.println(x);
obj.change(obj);
System.out.println(x);
}
}
Output: 50 100
-
This is not what call by reference means; se https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_reference. Call by reference means passing a reference to an arbitrary variable. What you are doing is passing a reference to an object. – Stephen C Jul 18 '21 at 05:47