Pass by Value and Pass by Reference in Java

Pass by Value:

Pass by Value is defined as the process of passing a copy of the parameters to the function in a way that the actual values aren’t changed as well as the task of the function is accomplished.

Pass by Reference:

Pass by Reference is defined as the process of passing the address or reference of the parameters to the function in a way that the actual values gets changed while accomplishing the task of the function and the modifications to the parameters gets reflected.

Function Overloading:

The most important advantage of Java over other languages is that it supports Polymorphism.

Polymorphism also known as Function Overloading is defined as the process where functions are declared with same names but for different purposes resulting in a different list of parameters and of different data types, passed as arguments. When such function is called, the parameters that are passed have to be checked and verified to ensure the correct function that has to be used or ‘overloaded’.

Example:

class Calculate {
    public int volume(int s) // Volume of Cube
    {
        return (s * s * s);
    }

    public int volume(int l, int b, int h) // Volume of Cuboid
    {
        return (l * b * h);
    }
}

Here the return type, access specifier and name of both the function are absolutely identical but the difference lies in the parameter list.

These functions are invoked using the objects that will be created in the main function:

public static void main()
{
    Calculate obj = new Calculate();
    int cube = volume(5);
    int cuboid = voulme(6, 7, 8);

    System.out.println("Area of Cube: " + cube);
    System.out.println("Area of Cuboid: " + cuboid);
}

When 5 is passed in the volume(), the result is returned back to the integer variable cube. Similarly, when 6,7,8 is passed in the volume(), the result is returned back to the integer variable cuboid as the volume of a cuboid with dimensions 6,7,8 respectively.

Pass by Value and Pass by Reference in Java