What is difference between actual parameters and formal parameters in java?
The correct answer and explanation is:
In Java, the terms actual parameters and formal parameters refer to values used in methods, but they have distinct roles.
Actual parameters are the values or variables passed to a method when it is called. These are the real data supplied to the method. Actual parameters are also called arguments in Java. For example, in the method call add(5, 10), the values 5 and 10 are actual parameters. They provide the input for the method to process.
Formal parameters, on the other hand, are the variables defined in the method signature to accept the values passed during the method call. They act as placeholders for the actual parameters. Formal parameters are specified when a method is defined, and they represent the values that will be used within the method. In the case of the method definition public void add(int a, int b), a and b are formal parameters.
The difference between the two lies primarily in their scope and usage:
- Scope: Actual parameters exist at the point where the method is called. Formal parameters exist only within the method’s body.
- Definition: Actual parameters are provided by the caller (e.g., values or variables), while formal parameters are part of the method’s declaration.
- Value Transfer: When a method is called, the values of the actual parameters are passed to the formal parameters. If the actual parameter is a primitive value, a copy of the value is passed (pass-by-value). If it’s an object, the reference to the object is passed.