Add/subtract
- Java course
- Beginner
- Lesson 20/116
- 6 min
Write add and subtract methods.
The add method
The first method of the calculator is add. It takes two ints, sums them and returns the result. It is static, so it is called directly, not via a class name.
static int add(int a, int b) {
return a + b;
}You can call it in main as add(5, 3); the result is 8. The same structure works for subtract: return a - b;.
Both methods return int because we work with integers.
Practice Add add and subtract methods
Add static int add(int a, int b) and static int subtract(int a, int b) methods to the existing Main class. add returns a + b, subtract returns a - b. Call both in main and print with println; keep the existing println call.
Starter code
public class Main {
public static void main(String[] args) {
System.out.println("Calculator");
}
}Sample solution
public class Main {
static int add(int a, int b) {
return a + b;
}
static int subtract(int a, int b) {
return a - b;
}
public static void main(String[] args) {
System.out.println("Calculator");
System.out.println(add(5, 3));
System.out.println(subtract(5, 3));
}
}Expected output
Calculator 8 2
When to use static?
Putting static before a method makes it callable without creating an object. The calculator methods are static because they're called directly from main.
Without static, you'd need to create an object first:
Main calc = new Main();
calc.add(5, 3);That's an extra step, so keeping helper methods static is more practical.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the method types
| Term | Meaning |
|---|---|
static |
Class-level |
int |
Returns integer |
void |
No return |
return |
Returns a value |
2 What does add(2, 3) return?
- 1
- 23
- 6
- 5 Correct answer
Explanation: add(2, 3) sums two numbers: 5.
3 Complete the return statement
static int add(int a, int b) { return a ____ b; }
static int add(int a, int b) { return a + b; }
Explanation: return a + b; performs addition.