Methods and return values
Define a method with typed parameters and return a result to its caller.
Describe the contract
A declaration such as static int area(int width, int height) names a method, declares the parameter types, and promises to return an int. A static helper belongs to the class and can be called from main without creating a separate instance.
How it works
At a call site, first identify the arguments and their declared types. Inside the method, use those values under the parameter names. When the method returns, put its result where the call expression appeared, such as into a variable or another calculation.
Return or print
A method declared with void has no result value. A method declared with int can return its result using return. Put calculation inside a return-value method and printing at the call site to keep the calculation reusable.
Code example
public class Main {
static int area(int width, int height) {
return width * height;
}
public static void main(String[] args) {
int totalArea = area(4, 3) + area(2, 5);
System.out.println(totalArea);
}
}Check your understanding
Add the areas of the listed rectangles. Each pair lists its width and height.
See the example and explanation
- Example 1
- Given
(2, 3), (1, 5) - Answer
11 - Example 2
- Given
(3, 3), (3, 3) - Answer
18
Multiply the width by height for each rectangle, then add the returned integers.