Tags

, ,

I would like to give you an example first. After that, I will explain what happens inside.

Let’s start with a Child class which has a field called ‘height’.

Child class:

package fun.sanjibsinha.classesandobjects;

public class Child extends Parent {
    public int height;
}

Now the main method:

package fun.sanjibsinha.classesandobjects;

public class Main {
static void passPrimitive(int y){
//invoking this method with a local variable
//cal this method with its own value
y = 11;
System.out.println("Value of y : " + y);
}
static void passingObject(Child child){
//invoking this method with a new instance
//always references to this object
// and reflects this value
child.height = 10;
System.out.println("Height of child object: " + child.height);
}

public static void main(String[] args) {
//call by value
int x = 2;
passPrimitive(x);
System.out.println("Value of x : " + x);
System.out.println();
Child childOne = new Child();
childOne.height = 100;
System.out.println("Height of childOne : " + childOne.height);
//call by reference
passingObject(childOne);
System.out.println("Height of childOne now refers to the previous child object : "
+ childOne.height);
}

}

Let us first see the output first:

Value of y : 11
Value of x : 2

Height of childOne : 100
Height of child object: 10
Height of childOne now refers to the previous child object : 10

In the above section of code, the primitive data type ‘int’ has been passed into methods as a primitive argument, as well as a value.

Any changes to the value of the parameters only exist in the method scope. When the method returns, any changes made to the parameters are lost instantly. Here exactly that happens. We made changes to the value of the parameter of the method ‘passPrimitive(int y)’; and, the method returns the value of ‘y’, but that does not affect the value of ‘x’.

In case of the objects, since the reference variable points the HEAP memory. The exactly opposite happens. The newly created reference type variable points to the previously created object and reflects its value. The changes made to the parameters are not lost.