Parameters are needed in order to pass values to the method. In the method, these values can be used as source data, outgoing data, and can also be changed during some operations.
Formal parameters describe the number and types of parameters that the method will take. For example, you have a function that calculates the sum of two numbers:
public static int sum(int num1, int num2)
{
return num1+num2;
}
n this function, the formal parameters are num1 and num2, which show that the method accepts 2 parameters of type int.
When a method is called, formal parameters are replaced by actual ones.
Actual parameters are those values that are passed to the method when it is called.
For example, you call the method created above:
public static void main(String[] args) {
System.out.println( sum(10,30) );
}
In this case, the actual parameters will be 10 and 30, which are substituted into the function instead of num1 and num2, respectively.
Substituting the actual values, we get:
public static int sum(int num1, int num2)
{
return num1/*=10*/+num2/*=30*/;
}
And so, formal parameters are used to describe the number and types of input parameters of the method
public static int sum(int num1, int num2)
and they are also used in the method, in the code it is:
return num1 + num2;
Actual parameters are values, which are substituted for formal parameters when calling a method.
Comments
Leave a comment