Multiply/divide
- Java course
- Beginner
- Lesson 21/116
- 6 min
Add multiply, divide and zero check.
multiply and divide
We'll add multiplication and division methods to the calculator. multiply multiplies two numbers, divide divides the first by the second.
static int multiply(int a, int b) {
return a * b;
}
static int divide(int a, int b) {
if (b == 0) {
return 0;
}
return a / b;
}divide has a divide by zero check: if b is zero, the method returns 0. This prevents the program from crashing. Java normally throws ArithmeticException when you try to divide by zero.
Practice Add multiply and divide methods
Add static int multiply(int a, int b) and static int divide(int a, int b) methods to the existing class. multiply returns a * b, divide returns a / b with a zero check. Print multiply(5, 3) and divide(10, 2) in main with println; keep the existing calls.
Starter code
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));
}
}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;
}
static int multiply(int a, int b) {
return a * b;
}
static int divide(int a, int b) {
if (b == 0) {
return 0;
}
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));
System.out.println(multiply(5, 3));
System.out.println(divide(10, 2));
}
}Expected output
Calculator 8 2 15 5
Division by zero
Integer division by zero throws ArithmeticException in Java. This stops the program and shows an error to the user.
To prevent this, our divide method checks b == 0 and safely returns 0. This is called defensive guarding.
In the next lesson we'll do the same with try/catch. That's another way to catch the error.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the multiply return
static int multiply(int a, int b) { return a ____ b; }
static int multiply(int a, int b) { return a * b; }
Explanation: return a * b; performs multiplication.
2 Match the operations
| Term | Meaning |
|---|---|
add |
Addition |
subtract |
Subtraction |
multiply |
Multiplication |
divide |
Division |
3 What does divide(10, 0) return in this code?
- 0 Correct answer
- Throws an error
- 10
- 1
Explanation: The zero check returns 0, no error.