Parameter passing methods:
In ‘Java’ language there are two ways that the
parameters can be passed to a function, they are
i). Call by value
ii).Call by reference
1. Call by value:
- This method copies the values of actual parameters into the formal
parameters of the function.
- Here, the changes in the formal parameters cannot affect the actual
parameters, because formal arguments are a photocopy of actual arguments.
- Note: If no idea about actual and formal arguments
means the below link to use for learning this topic.
Example program:
public class Call_by_value {
void
display() {
int n
= 2;
System.out.println("The " + n + " of cubic value is
" + cube_func(n));//function calling
}
int
cube_func(int x) {
x = x
* x * x;
return (x);
}
public
static void main(String args[]) {
Call_by_value
c = new Call_by_value();
c.display();
}
}
Output:
2. Call by reference:
- It is another way of passing parameters to the function.
- Here, the address of arguments is copied into the parameters inside the
function, the address is used to access the actual arguments used in the call.
- Hence changes made in the arguments are permanent.
- Here pointers are passed to function, just like any other arguments and we
need not declare the parameters as a pointer type.
Example program:
public class Call_by_reference {
void display() {
int a = 5, b = 7;
interchange_func(a, b);//pass
address to the function
}
void interchange_func(int x, int
y) {
System.out.println("a
and b values before interchanging : " + x + " " + y);
int t;
t = x;
x = y;
y = t;
System.out.println("a
and b values after interchanging : " + x + " " + y);
}
public static void main(String
args[]) {
Call_by_reference r = new
Call_by_reference();
r.display();
}
}
Output:
Recursion:
- It is the process being performed where one of the instructions is to
“repeat the process”.
- This makes it sound very similar to a loop because it repeats the same
code, and in some ways, it is similar to looping.
- It is the process of calling the same function itself again and again until
some condition is satisfied. This process is used for repetitive computation in
which each action is satisfied in terms of a previous result.
import java.util.Scanner;
public class Recursion_Demo {
int a;
void get_data() {
Scanner sc = new
Scanner(System.in);
System.out.print("Enter
the factorial number: ");
a = sc.nextInt();
}
int recursive_func(int x)//
function declaration
{
int f;
if (x == 1) {
return (1);
} else {
f = x * recursive_func(x
- 1);// recursive function
}
return (f);
}
void display() {
System.out.print("The
factorial of " + a + "! = " +
recursive_func(a)+"\n");// function call
}
public static void main(String
args[]) {
Recursion_Demo r = new
Recursion_Demo();
r.get_data();
r.display();
}
}
Output: