Beyond Basic Math: The Java Math Class
In the previous guide, we looked at +, -, *, and /. But what if you need to calculate $5^3$ or find the square root of a number? For these, Java provides the built-in Math class.
Unlike the Scanner, the Math class is automatically available—you don’t need to import anything!
1. Common Math Methods
All Math methods are "static," meaning you call them directly using the word Math.
| Method | What it does | Example | Result |
|---|---|---|---|
Math.max(a, b) |
Returns the largest number | Math.max(10, 20) |
20 |
Math.min(a, b) |
Returns the smallest number | Math.min(5, 2) |
2 |
Math.sqrt(x) |
Returns the Square Root | Math.sqrt(16) |
4.0 |
Math.pow(a, b) |
Returns $a$ to the power of $b$ | Math.pow(2, 3) |
8.0 |
Math.abs(x) |
Returns the Absolute value | Math.abs(-5) |
5 |
2. Rounding Numbers
Working with decimals (double) often results in long numbers. You can clean them up using these methods:
Math.round(x): Rounds to the nearest whole number (e.g.,3.5becomes4).Math.ceil(x): Rounds UP (e.g.,3.1becomes4.0).Math.floor(x): Rounds DOWN (e.g.,3.9becomes3.0).
💻 Full Practical Example: The Hypotenuse Calculator
Do you remember the Pythagorean theorem ($a^2 + b^2 = c^2$)? We can use the Math class to solve for $c$ (the hypotenuse) easily.
import java.util.Scanner;
public class HypotenuseCalc {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter side A: ");
double a = scanner.nextDouble();
System.out.print("Enter side B: ");
double b = scanner.nextDouble();
// Calculate c = square root of (a^2 + b^2)
double c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
System.out.println("The hypotenuse is: " + c);
scanner.close();
}
}
3. Math Constants
The Math class also provides extremely accurate values for mathematical constants. No need to type out 3.14159... manually!
Math.PI: The ratio of a circle's circumference to its diameter ($\approx 3.14159$).Math.E: The base of natural logarithms ($\approx 2.718$).
Usage: double area = Math.PI * Math.pow(radius, 2);
💡 Challenge: The Power Play
Write a program that asks the user for a base and an exponent. Use Math.pow() to calculate the result and print it.
Bonus: Use Math.max() to tell the user which of their two inputs was larger!