Computer Applications
How is call-by-value way of function invoking different from call-by-reference way ? Give appropriate examples supporting your answer.
User Defined Methods
1 Like
Answer
In call by value, the called function creates its own work copy for the passed parameters and copies the passed values in it. Any changes that take place remain in the work copy and the original data remains intact.
In call by reference, the called function receives the reference to the passed parameters and through these references, it accesses the original data. Any changes that take place are reflected in the original data.
This can be clearly understood by the example given below:
public class DemoFnCalls
{
public static int x = 10 ;
public static int y = 20 ;
public void DemoTest() {
System.out.println("Values initially. x =" + x + ", y =" + y);
swapCallByValue(x, y);
System.out.println("Values after swapCallByValue method. x ="
+ x + ", y =" + y) ;
DemoFnCalls object1 = new DemoFnCalls( ) ;
swapCallByRef(object1);
System.out.println ("Values after swapCallByRef method. x ="
+ x + ", y =" + y) ;
}
public static void swapCallByValue(int a, int b) {
int tmp;
tmp = a;
a = b;
b = tmp;
System.out.println("Values inside swapCallByValue method. x ="
+ a + ", y = " + b);
}
public static void swapCallByRef(DemoFnCalls obj) {
int tmp;
tmp = obj.x;
obj.x = obj.y;
obj.y = tmp;
System.out.println("Values inside swapCallByRef method. x ="
+ obj.x + ", y =" + obj.y);
}
}
Answered By
2 Likes
Related Questions
Which of the following function-definitions are overloading the method given below :
int sum(int x, int y) {}
- int sum(int x, int y, int z) { }
- float sum(int x, int y) { }
- int sum (float x, float y) { }
- int sum (int a, int b) { }
- float sum(int x, int y, float z) { }
What is the role of void keyword in declaring functions ?
What is the output of the following program ? Justify your answer.
class Check { public static void chg (String (nm) ) { nm = "Aamna" ; // copy "Aamna" to nm } public void test( ) { String name= "Julius"; System.out.println (name); chg(name); System.out.println(name); } }
Write a function that takes two char arguments and returns 0 if both the arguments are equal. The function returns -1 if the first argument is smaller than the second and 1 if the second argument is smaller than the first.