In Writing and calling methods, the careForBaby
method did the same thing each time it was called (printed the same 3 lines). Programmers often want methods to perform differently each time they are called. A method can accept one more more parameters. The values of parameters can be used to affect how the method behaves when it is called.
It is up to the programmer to determine how the values of parameters are used. The values can be used as part of output. The values can be used to control which lines of code are executed.
Program using method with parameters
private static void careFor(String name, boolean isBaby)
{
System.out.println("Feed " + name);
if(isBaby)
{
System.out.println("Burp " + name);
System.out.println("Change " + name);
}
}
public static void main(String[] args)
{
careFor("Evan", false);
careFor("Aubrey", true);
}
A method header specifies the type and name of each parameter in the parentheses to the right of the method name.
private static void careFor(String name, boolean isBaby)
Method careFor
accepts 2 parameters, String name
and boolean isBaby
. Parameters specified in a method header are known as formal parameters.
Each call to a method specifies values for each of the method’s parameters.
The call careFor("Evan", false);
passes "Evan"
as the value of name
and false
as the value of isBaby
.
The call careFor("Aubrey", true);
passes "Aubrey"
as the value of name
and true
as the value of isBaby
.
The values passed to a method when it is called are known as actual parameters or arguments.
The careFor
method uses the value of its parameter name
as part of the output. See Working with String objects for details on concatenation and other things that can be done with String
objects.
The careFor
method uses the value of its parameter isBaby
to determine whether or not to print 2 additional lines. See Working with boolean variables for additional information.
When writing the code inside a method that accepts parameters, assume that each parameter already has a value. The values of parameters are set when the method is called, not within the method itself.
Output
Feed Evan
Feed Aubrey
Burp Aubrey
Change Aubrey
Pass by value
All arguments in Java are passed by value. A call to a method passes a copy of the value of each argument to the method. See Primitive types vs references exercises with method calls for a detailed demonstration.
Methods with return values
A Java method can return 0 or 1 value to the code that called the method. See Methods with return values for details.