educative.io

Introduction to Variables - A Complete Guide to Java Programming

CODE SNIPPET:

class ReferenceVariable {

int num;

}

public class ExampleFourteen {

public static void main(String[] args) {

    int i = 10;

    int j = 5;

    System.out.println(i + " " + j);

    i = j;

    System.out.println(i + " " + j);

    j++;

    System.out.println(i + " " + j);

    ReferenceVariable numOne = new ReferenceVariable();

    ReferenceVariable numTwo = new ReferenceVariable();

    System.out.println(numOne.num + " " + numTwo.num);

    numOne = numTwo;

    numOne.num = 10;

    System.out.println(numOne.num + " " + numTwo.num);

    numTwo.num = 100;

    System.out.println(numOne.num + " " + numTwo.num);

    numTwo.num++;

    System.out.println(numOne.num + " " + numTwo.num);

}

}

Hi! I am not able to understand the difference between call by reference and call by value.

My understanding is that numOne and NumTwo are two separate objects. Both have instance variables num (from class ReferenceVariable) separate from each other.

I would really appreciate if you could help me explain it. Thanks!

Hi @Bhupesh_Duggal,
Welcome to the Discuss community!

Let’s first understand how variables and objects are different from each other. The variables are created in the Stack, and they are actual data variables to hold data. In contrast, the objects are created in Heap, and they are actually pointers that save the address of the object in memory.

Now, the numOne and numTwo are two objects of the ReferenceVariable class. Both are pointing to different objects. When we assign an object, numTwo, to another object, numOne, it doesn’t change the value of numOne, but it holds the reference of the numTwo. Now numOne and numTwo both are pointing to the same object. So, whenever we make a change to any of these, the change happens to the same object, which is visible in the code.

I hope you understand the difference between call by value and call by reference. If you’ve any other queries, feel free to reach.