In: Computer Science
Discuss the concept of parameters. What are parameters for? What is the difference between formal parameters and actual parameters? Give an example in Java code that illustrates formal parameters and actual parameters.
Parameters:
The data that is received by the method is known as a parameter.
For example:
void add(int a, int b);
In the above method, 'a' and 'b' are parameters.
When we call a method and want to pass some information to the called function then we use parameter. So, the parameters are used to pass the information.
Formal Parameter:
In a method, the identifier that is used to store the value passed by the calling method is the formal parameter.
void add(int a, int b);
In the above method, 'a' and 'b' are formal parameters.
Actual Parameter:
In a calling method, the actual value passed into the method is the actual parameter.
add(10, 20);
In the above method, '10' and '20' are actual parameters.
Difference between actual parameter and formal parameter:
For example:
public class Main
{
//method to add two numebrs
//the variable 'a' and 'b' are formal parameter
public static int add(int a, int b)
{
return a+b;
}
public static void main(String[] args)
{
//method calling
//'10' and '20' are actual parameter
int c = add(10, 20);
//display sum
System.out.println("Sum = " +
c);
}
}