In programming, parameters are variables that are used to pass values into a function or method. They define the input that a function requires to perform its task. When invoking or calling a function, we provide actual values for these parameters, which are referred to as actual parameters. On the other hand, the variables defined in the function declaration are referred to as formal parameters.
Formal parameters act as placeholders for the actual values that will be passed when the function is called. These parameters define the type, name, and order of the values that the function expects to receive. They serve as a contract between the caller and the function, ensuring that the correct values are successfully passed.
Here's an example in Java code to illustrate formal and actual parameters:
```java
public class Example {
public static void main(String[] args) {
int a = 5;
int b = 10;
// The function call with actual parameters 5 and 10
int result = sum(a, b);
System.out.println("The sum is: " + result);
}
// The function declaration with formal parameters num1 and num2
public static int sum(int num1, int num2) {
return num1 + num2;
}
}
```
In the above example, we have a method called `sum` that takes two formal parameters `num1` and `num2`. These formal parameters define the type of values (integers) that the function expects to receive.
In the `main` method, we declare two variables `a` and `b` with actual values 5 and 10 respectively. When we call the `sum` method with `a` and `b` as actual parameters, the values are passed to the formal parameters `num1` and `num2`. The function then performs the addition operation and returns the result, which is stored in the variable `result`. Finally, we print the result to the console.
Discuss the concept of parameters. What are the parameters? What is the difference between formal parameters and actual parameters? Give an example in Java code that illustrates formal parameters and actual parameters.
1 answer