Java Reference
In-Depth Information
Multiple Parameters
So far, our discussion of parameter syntax has been informal. It's about time that we
wrote down more precisely the syntax we use to declare static methods with parameters.
Here it is:
public static void <name>(<type> <name>, ..., <type> <name>) {
<statement>;
<statement>;
...
<statement>;
}
This template indicates that we can declare as many parameters as we want inside
the parentheses that appear after the name of a method in its header. We use commas
to separate different parameters.
As an example of a method with multiple parameters, let's consider a variation of
writeSpaces . It is convenient that we can use the method to write different numbers
of spaces, but it always writes spaces. What if we want 18 asterisks or 23 periods or
17 question marks? We can generalize the task even further by having the method
take two parameters—a character and a number of times to write that character:
public static void writeChars(char ch, int number) {
for (int i = 1; i <= number; i++) {
System.out.print(ch);
}
}
The character to be printed is a parameter of type char , which we will discuss in
more detail in the next chapter. Recall that character literals are enclosed in single
quotation marks.
The syntax template for calling a method that accepts parameters is the following:
<method name>(<expression>, <expression>, ..., <expression>);
By calling the writeChars method you can write code like the following:
writeChars('=', 20);
System.out.println();
for (int i = 1; i <= 10; i++) {
writeChars('>', i);
writeChars(' ', 20 - 2 * i);
writeChars('<', i);
System.out.println();
}
 
Search WWH ::




Custom Search