Math class
- Java course
- Beginner
- Lesson 16/116
- 4 min
Learn math operations with Math.abs and Math.max.
What is the Math class?
The Math class holds the mathematical methods from the Java standard library. All methods are static, so you call them as Math.methodName without creating an object.
Common methods:
Math.abs(x): absolute valueMath.max(a, b): maximumMath.min(a, b): minimumMath.pow(base, exp): powerMath.sqrt(x): square root
Constants: Math.PI, Math.E.
Practice Use Math.abs and Math.max
Write a Main class with a main method. Assign -5 to int a and 9 to int b. Print Math.abs(a) and Math.max(a, b) with println.
Sample solution
public class Main {
public static void main(String[] args) {
int a = -5;
int b = 9;
System.out.println(Math.abs(a));
System.out.println(Math.max(a, b));
}
}Expected output
5 9
Math constants
The Math class has two useful constants: Math.PI (π ≈ 3.14159) and Math.E (e ≈ 2.71828).
double radius = 5.0;
double circumference = 2 * Math.PI * radius;
// ≈ 31.4159These constants are static final: class-level and immutable. Writing Math.PI = 3.0; gives a compile error.
Using these constants in your own math is safer than typing the value by hand.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does Math.max(3, 7) return?
- 7 Correct answer
- 10
- 21
- 3
Explanation: Math.max returns the larger of two values.
2 Match the Math methods
| Term | Meaning |
|---|---|
Math.abs |
Absolute |
Math.max |
Maximum |
Math.min |
Minimum |
Math.pow |
Power |
3 Complete the Math method call
int big = Math.____(5, 3);
int big = Math.max(5, 3);
Explanation: Math.max(5, 3) returns 5.