CS1102 Discussion Assignment Unit 3 - Formal parameters and actual parameters

Questions

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.

1. Concept

There are two kinds of parameters: formal parameter and actual parameter.

Formal parameter: Some books call it parameter for short. It is “a piece of information that a method requires before it can run. Formal parameters are variables: they contain values and have types” (Downey, 2019, p. 65).

Actual parameter: It is also called argument. It is “a value that you provide when you call a method. This value must have the type that the method expects” (Downey, 2019, p. 65).

The difference: Formal parameters are the variables in the method’s parentheses, while actual parameters are the values passing to the formal parameters.

2. Example

Codes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package discussion_assignment;

/**
* This is an example of formal parameters and actual parameters,
* which calculates the area of the rectangular.
*/
public class CalculateArea {
public static void main(String[] args) {
// call the method
double result = rectangularArea(2.0, 3.0);
System.out.printf("The area of the rectangular is: %f", result);

}

// define a static method
public static double rectangularArea(double a, double b) {
double area = a * b;
return area;
}
}

Outputs:

1
2
The area of the rectangular is: 6.000000
Process finished with exit code 0

Explanation:
In the above example, there are two static methods in the class CalculateArea: the main() and the rectangularArea().

The rectangularArea() method has two formal parameters: double a, double b.

In the main() method, I called the method rectangularAreain() (double result = rectangularArea(2.0, 3.0);), which assigned 2.0 to the formal parameter a, and 3.0 to the formal parameter b, respectively. The numbers 2.0 and 3.0 are the actual parameters.

Word count: 263

References

1.Downey, A.B. & Mayfield, C. (2019). Think Java (2nd ed.). Green Tea Press.
https://open.umn.edu/opentextbooks/formats/331

​


This is the ending, thanks for reading.