Pass by Reference vs Pass by Value

You already know that the data types are broadly divided into primitive types and anything that is not a primitive is an object type. Primitives are; byte, char, short, int, long, float, boolean and double. Everything else is an object.

When it comes to sending the variables as arguments to a method or constructor, if primitive variables are used, then the literal values that the primitive variable hold are copied over to the respective parameters of the method or construct.

If on the other hand, if an object is passed as the argument value, then the reference of the object is passed over and not the object copy itself. Let us understand this concept with some examples;


package com.mbcc.tutorial.chapter4;

public class PassingByReferenceValue {

    public static void main(String[] args) {
        int a = 10;
        MyObject myObject = new MyObject();
        myObject.setA(10);

        doubleMe(a, myObject);
        System.out.println("a value inside main method = " + a);
        System.out.println("a value of object inside main method = " + myObject.getA());
    }

    public static void doubleMe(int a, MyObject m) {
        a = a * 2;
        System.out.println("a value inside doubleMe method = " + a);

        m.setA(m.getA() * 2);
        System.out.println("a value of object inside doubleMe method = " + m.getA());
    }

}

class MyObject {
    int a;

    public int getA() {
        return a;
    }

    public void setA(int a) {
        this.a = a;
    }

}

Run the above program and what do you notice? and Why? Let us try to understand

You see the primitive arguments are copied over to the respective parameters for the doubleMe method which is also called pass-by-value. However the MyObject data type is pass-by-reference to the method

Pass-by-reference means to pass the reference of an argument in the calling method to the corresponding formal parameter of the called method. The called method can modify the value of the original object by taking the reference value. Where as when it comes to the primitives, they are copied over as a new value and hence the original variable is not available to the called method.

The main difference between pass-by-reference and pass-by-value is that modifications made to arguments passed in by reference in the called method have effect in the calling method, whereas modifications made to arguments passed in by value in the called method can not affect the calling method.

results matching ""

    No results matching ""