Passing Parameters
Passing Parameters
in Java
Parameters
• Parameters are the way Java programs pass
information to methods
• When declaring methods:
– Each parameter is a type declaration (I.e. type
followed by parameter name)
– No semicolon at end. Instead separate them by
commas
– Unlike type declarations, can’t initialize
Passing Parameters
• When we call a method, we must pass the
parameters it expects
– In parentheses after the method name
– Separated by commas
– Example: PrintAverage(4.0,6.0);
• Parameters can be values, variables, or
expressions:
– PrintAverage(4.0,6.0);
– PrintAverage(a,b);
– PrintAverage(x-9,x+3);
Example
• Suppose we want a method to average two numbers:
public static void
PrintAverage(double num1, double num2) {
... //Body of function
}
• Receives two parameters, both double
• Examples:
– PrintAverage(6.0,8.0)
– When PrintAverage runs, num1 becomes 6.0, num2 becomes 8.0.
Some Vocabulary
• The parameters a method expects are called
formal parameters
– E.g. PrintAverage(double num1,
double num2)
– num1 & num2 are formal parameters
• Parameters values passed to the method are
called actual parameters
– 4.0 and 6.0 are actual parameters:
PrintAverage(4.0,6.0);
– a and b are actual parameters:
PrintAverage(a,b);
Declaring Variables in Methods
• When a variable is declared in a method, it
exists only in that method
• If you want to use it in another method, you
must declare it again there
• The variables in these two methods are now
different. I.e. When one changes the other
stays the same.
Declaring Variables in Methods
Example
public static void main(String[] args){
double num1=2.0; //Two different num1’s
double num2=4.0;
printAverage(num1,num2);
}
public static void PrintAverage
(double num1, double num2) {
num1 = (num1+num2)/2;
System.out.println(num1);
}
Num1 in main set to 2.0
public static void main(String[] args){
double num1=2.0; Main:
Num1:2.0
double num2=4.0; Num2:
PrintAverage:
printAverage(num1,num2); Num1:
} Num2: