Pass by Reference

This lesson explains the concept of pass by reference.

We'll cover the following...
1.

What is passing by reference?

0/500
Show Answer
Did you find this helpful?

Note that objects are always created in heap memory and the program variables are only references or addresses to them. So, when we pass a reference data type, the address of the object in the heap memory is copied and passed along. The receiving method can use the reference or the address to manipulate the object in the heap.

Press + to interact
Java
import java.util.*;
class Demonstration {
public static void main( String args[] ) {
SuperList obj = new SuperList(5);
System.out.println("superList = " + obj.sList);
}
}
class SuperList {
public List<Integer> sList;
public SuperList(int n) {
List<Integer> superList = null;
allocate(superList, n);
sList = superList;
}
void allocate(List<Integer> list, int n) {
}
}
1.

What will be the output of the run method for the IntegerSwap class below?

public class IntegerSwap {

    public void run() {
        Integer x = 5;
        Integer y = 9;
        System.out.println("Before Swap x: " + x + " y: " + y);
        swap(x, y);
        System.out.println("After Swap x: " + x + " y: " + y);
    }

    private void swap(Integer a, Integer b) {
        Integer temp = a;
        a = b;
        b = temp;
    }
}
0/500
Show Answer
Did you find this helpful?
Press + to interact
Java
class IntegerSwap {
public static void main( String args[] ) {
(new IntegerSwap()).run();
}
public void run() {
Integer x = 5;
Integer y = 9;
System.out.println("Before Swap x: " + x + " y: " + y);
swap(x, y);
System.out.println("After Swap x: " + x + " y: " + y);
}
private void swap(Integer a, Integer b) {
Integer temp = a;
a = b;
b = temp;
}
}

As you can see from the diagram, a and b appear as stack variables holding addresses of integer object locations. Once the program control returns back to the run method, the x and y keep pointing to the same integer objects in heap because they passed in the references or the addresses of the integer objects and not themselves.

Technical Quiz
1.

What value will be printed from the following snippet?

        String[] students = new String[10];
        String studentName = "You are an awesome developer";
        students[0] = studentName;
        studentName = null;
        System.out.println(students[0]);
A.

You are an awesome developer

B.

null


1 / 1
Press + to interact
Java
class Demonstration {
public static void main( String args[] ) {
String[] students = new String[10];
String studentName = "You are an awesome developer";
students[0] = studentName;
studentName = null;
System.out.println(students[0]);
}
}