Java
In this tutorial we will learn about call by reference in Java programming language.
In the previous tutorial we learned about Call by value in Java. Feel free to check that out.
In Java, call by reference is not there. If you know C programming language they you know that we can pass address of a variable to a function and manipulate its value via the address.
But Java passes everything as value. So, to simulate the call by reference we can pass an object to a method as an argument.
In the following example we are passing object as an argument to a method. So, any change made in the called method is going to be reflected back in the calling method.
class Addition {
public void add100(Example obj) {
System.out.println("In add100() method of Addition class.");
System.out.println("Value of n before addition: " + obj.n);
obj.n = obj.n + 100;
System.out.println("Value of n after addition: " + obj.n);
System.out.println("Returning back to the calling method.");
}
}
public class Example {
// variable
public int n;
// constructor
Example(int n) {
this.n = n;
}
// method
public static void main(String[] args) {
// create Example object and set value of n
Example exampleObj = new Example(10);
// create Addition object
Addition additionObj = new Addition();
System.out.println("In main() method of Example class.");
System.out.println("Value of n before call: " + exampleObj.n);
// pass an integer value
System.out.println("Passing exampleObj to add100() method of Addition class.");
additionObj.add100(exampleObj);
System.out.println("Back from add100() method of Addition class.");
System.out.println("In main() method of Example class.");
System.out.println("Value of n after call: " + exampleObj.n);
}
}
Output:
$ javac Example.java
$ java Example
In main() method of Example class.
Value of n before call: 10
Passing exampleObj to add100() method of Addition class.
In add100() method of Addition class.
Value of n before addition: 10
Value of n after addition: 110
Returning back to the calling method.
Back from add100() method of Addition class.
In main() method of Example class.
Value of n after call: 110
In the above code we are creating exampleObj
object of the Example
class and setting the value of n
to 10 via its constructor.
Then we are creating another object additionObj
of the Addition
class and passing the exampleObj
object as an argument to the add100()
method of the Addition
class.
Inside the add100()
method we are add 100 to n
of the exampleObj
object of the Example class.
So, when we return back from the called method add100()
to the calling method main()
we can still see the change made to n
of the exampleObj
object.
And this is because when we pass the exampleObj
as an argument to the add100()
method, the obj
parameter of the add100()
method gets the reference of the object and hence it also points at the same object in memory like exampleObj
object.
ADVERTISEMENT