Summary - Methods
- Java course
- Beginner
- Lesson 76/116
- 5 min
Combine return, overloading and scope to write a math helper.
Summary: Methods
In this group you saw the basics of methods: static definition, returning values with return, void methods, overloading and scope.
A method does one job; when called, the flow enters it, and when done, it returns. With overloading you can reuse the same name with different parameters.
Now you will combine these to write a small calculator helper: define and use add, square and printResult methods.
Practice Calculator helper
Define two methods: static int add(int a, int b) returns the sum; static void printResult(int r) prints Result: r. From main, call printResult(add(7, 8)).
Starter code
public class Main {
public static void main(String[] args) {
// Call the print method with the result of the add method
}
// Define static int add(int a, int b)
// Define static void printResult(int r)
}Sample solution
static int add(int a, int b) { return a + b; }
static void printResult(int r) {
System.out.println("Result: " + r);
}
// inside main:
printResult(add(7, 8));Expected output
Result: 15
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What defines a method's signature?
- Return type and name Correct answer
- Only the name
- Name and parameter types
- Body and return type
Explanation: Signature = name + parameter types; return type is not included.
2 Fill in the blank: call the method
int sum = add(3, ____);
int sum = add(3, 4);
Explanation: The add(3, 4) call returns the sum.
3 Match concept to explanation
| Term | Meaning |
|---|---|
return |
Hands a value out |
void |
Returns no value |
overloading |
Same name, different signature |
scope |
Block where a variable is valid |