What is the difference between actual parameters and formal parameters in Java?
In Java, actual arguments and formal parameters are two concepts of method parameters.
Actual parameters are the values that are passed to a method during a method call. The values of actual parameters can be constants, variables, expressions, or the return values of methods. The purpose of actual parameters is to provide the necessary data to a method.
Parameters in a method definition are variables used to receive the actual argument values when the method is declared. Parameters define the data type and number of arguments that a method can receive.
The differences are as follows:
- The difference in position: actual parameters refer to the values passed to a method when it is called, while formal parameters are the parameters defined within the method.
- Different data types: actual parameters can be constants, variables, expressions, or the return values of methods, while formal parameters are variables defined in the method to receive the values of actual parameters.
- The roles are different: the purpose of actual parameters is to provide the necessary data for the method, while the purpose of formal parameters is to define the data type and number of parameters that the method accepts.
For example:
public void printSum(int a, int b) {
int sum = a + b;
System.out.println("Sum is: " + sum);
}
public static void main(String[] args) {
int x = 5;
int y = 10;
printSum(x, y);
}
In this example, int a and int b are the formal parameters, as they define the data types and the number of parameters that the method receives. x and y are the actual parameters, as they are the values passed to the method when it is called.