Methods, Parameters, and Return Values
Define and call methods with parameters, return values, local variables, scope, static context, and decomposition.
A lesson of AP Computer Science A, in Control Flow and Methods, about 10 minutes.
By the end of this lesson, you will be able to define and call methods with parameters, return values from methods, and understand scope and method design.
Why Methods?
Methods serve two essential purposes:
- Code reuse: write once, call many times
- Abstraction: hide complexity behind a simple interface
A method is named block of code that performs a specific task. Well-named methods make code read like plain English.
Method Definition Syntax
accessModifier returnType methodName(parameterList) {
// method body
return value; // if returnType is not void
}
Example:
public static double area(double radius) {
return Math.PI * radius * radius;
}
Parameters vs. Arguments
// radius is the PARAMETER:
public static double area(double radius) { ... }
// 5.0 is the ARGUMENT:
double circleArea = area(5.0);
Parameters: variables declared in the method's signature. They receive values when the method is called.
Arguments: the actual values passed when calling the method.
Pass by value: Java passes copies of primitive values (int, double, boolean) to methods. The method cannot change the original variable.
public static void addOne(int x) {
x = x + 1; // changes only the local copy
}
int n = 5;
addOne(n);
System.out.println(n); // still 5!
For objects, the reference is passed by value — the method can modify the object's state but cannot make the variable point to a different object.
Return Values
public static void printGrade(int score) {
if (score >= 90) System.out.println("A");
else System.out.println("B");
}
void: the method performs an action but returns nothing.
Non-void: the method computes and returns a value of the declared type.
public static int max(int a, int b) {
if (a > b) return a;
return b;
}
int result = max(7, 3); // result = 7