D.1.10 Describe how data items can be passed to and from actions as parameters.
Parameters are identifiers listed in parentheses next to the subprogram name;
Sometimes called formal parameters;
Parameters are used to accept values from the method call;
A method declaration can include method parameters, which accept values from the method call.
The data passed to the method can then be used inside the method to perform its task.
In Java, you can choose the name of a method’s formal parameter without any concern that this name will be the same as an identifier used in some other method.
Formal parameters are really local variables, and so their meanings are confined to their respective method definitions.
public static void drawBar(int length) {
for (int i = 0; i < length; i++) {
System.out.print("*");
}
System.out.println();
}
Data is given, or passed, to a method by enclosing the data in parentheses in the method call. The value or variable passed to a method is called the argument.
the RightTriangle application makes six calls to drawBar().
Each call passes a different variable argument:
public class RightTriangle {
public static void drawBar(int length) {
for (int i = 1; i <= length; i++) {
System.out.print("*");
}
System.out.println();
}
public static void main(String[] args) {
/* draw a right triangle with base size 6 */
for (int i = 1; i <= 6; i++) {
drawBar(i); //method call with an argument (i) as value of parameter of the drawBar method above
}
}
}
*
**
***
****
*****
******
In Java, arguments are passed by value, which means that the data stored in an argument is passed.
An argument that is a primitive data type gives the method a copy of its value.
An argument that is an object gives the method a copy of its reference that points to methods for changing object data.
Therefore, a method can change the data stored in an object because it has access to the object’s methods, but it cannot change the data stored in a primitive variable because the method does not have access to the actual location of the primitive data.
When a method declaration includes more than one parameter, the parameters are separated by commas.
a modified drawBar() has an int parameter for the length of the bar and a String parameter for the character to use to draw the bar:
public static void drawBar(int length, String symbol) {
for (int i = 1; i <= length; i++) {
System.out.print(symbol);
}
System.out.println();
}
public static void main(String[] args) {
/* draw a right triangle with base size 6 */
for (int i = 1; i <= 6; i++) {
drawBar(i,"@"); //method call with two arguments as values of parameters
//of the drawBar method above
}
}