Passing by Reference means the called functions’ parameter will be the same as the callers’ passed argument (not the value, but the identity – the variable itself). Pass by value means the called functions’ parameter will be a copy of the callers’ passed argument.
Actual Parameter: The value that is passed to the function during function call is known as actual parameter.
Formal Parameter: The argument list in the function prototype is known as the Formal Parameter.
In Pass by Reference any changes made to the formal parameter is reflected in the actual parameter as both read the values from the same memory location.
In Pass by Value any changes made to the formal parameter is not reflected in the actual parameter as both store their information in separate memory locations.
Example of pass by reference:
Write a program to design a class Distance with the following features:
1. Data Members:
a. km – int -To store the number of kilometers
b. m – int – To store the number of meters
Given that a distance is measured in Kilometers and Meters.
2. Member Methods:
a. void input() To input the distance in Kilometers and meters
b. void display() To Print the distance
c. Distance add(Distance d1, Distance d2) This function takes two distances and returns the sum of the distances through a Distance object.
d. Distance diff(Distance d1, Distance d2) This function takes two distances and returns the difference in the distance through a Distance object.
import java.util.*;
public class Distance
{
int km, m;
void input()
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the distance in Kilometres:");
km = sc.nextInt();
System.out.println("Enter the distance in Metres:");
m = sc.nextInt();
}
void display()
{
System.out.println("The distance is: "+km+" kms "+m+" metres");
}
Distance add(Distance d1, Distance d2)
{
int tot = (d1.km+d2.km)*1000+d1.m+d2.m;
Distance sum = new Distance();
sum.km = tot/1000;
sum.m = tot%1000;
return sum;
}
Distance Diff(Distance d1, Distance d2)
{
int tot1 = d1.km*1000+d1.m;
int tot2 = d2.km*1000+d2.m;
int diff = Math.abs(tot1-tot2);
Distance dif = new Distance();
dif.km = diff/1000;
dif.m = diff%1000;
return dif;
}
void check(Distance d)
{
System.out.println("Referencing is here.");
d.km = 100;
}
public static void main()
{
Distance ob1 = new Distance();
Distance ob2 = new Distance();
Distance ad, df;
ob1.input();
ob2.input();
System.out.println("Distance 1:");
ob1.display();
System.out.println("Distance 2:");
ob2.display();
ad = ob1.add(ob1, ob2);
df = ob1.Diff(ob1, ob2);
System.out.println("Sum: ");
ad.display();
System.out.println("Difference: ");
df.display();
}
}