Java provides ready-made calculations in the Math class, part of the java.lang package. Because java.lang is imported automatically, you can use Math without any import (ICSE Class 9).
1The Math class methods
Call these on the class name Math. Each returns a result:
| Method | Returns | Example |
|---|---|---|
Math.pow(a, b) | a to the power b | Math.pow(2, 3) = 8.0 |
Math.sqrt(x) | Square root | Math.sqrt(25) = 5.0 |
Math.cbrt(x) | Cube root | Math.cbrt(27) = 3.0 |
Math.abs(x) | Absolute (positive) value | Math.abs(-7) = 7 |
Math.max(a,b) / Math.min(a,b) | Larger / smaller | Math.max(4, 9) = 9 |
Math.ceil(x) | Rounds UP to a whole number | Math.ceil(4.1) = 5.0 |
Math.floor(x) | Rounds DOWN | Math.floor(4.9) = 4.0 |
Math.round(x) | Rounds to the NEAREST whole | Math.round(4.5) = 5 |
Math.random() | A random decimal from 0 up to (not including) 1 | 0.37… |
Note the rounding trio: ceil always goes up, floor always goes down, round goes to the nearest.
Key points
- Math methods are called on the class: Math.sqrt(25), Math.pow(2,3).
- ceil rounds up, floor rounds down, round goes to the nearest whole.
- Math.random() gives a decimal from 0 up to (not including) 1; pow/sqrt/cbrt/abs/max/min do the obvious maths.
2Formulas into Java expressions
To use a maths formula in Java, rewrite it with operators and Math methods:
| Maths | Java |
|---|---|
| area = π r² | area = 3.14 * Math.pow(r, 2); |
| c = √(a² + b²) | c = Math.sqrt(Math.pow(a,2) + Math.pow(b,2)); |
| avg = (a + b + c) / 3 | avg = (a + b + c) / 3.0; |
Watch integer division:
5 / 2 gives 2 (not 2.5) because both are ints. Use a decimal — 5 / 2.0 — to get 2.5. Use brackets to keep the order of operations correct.Key points
- Replace powers with Math.pow and roots with Math.sqrt; keep brackets to preserve order.
- Integer division drops the decimal: 5 / 2 = 2; use 5 / 2.0 for 2.5.
- Test the expression with known numbers to check it's right.
★ Practical: calculate with Math
In BlueJ, write programs that:
- Read a number and print its square root and its cube.
- Read two numbers and print the larger using Math.max.
- Show the difference between Math.ceil, Math.floor and Math.round on 4.5.
- Compute the hypotenuse √(a² + b²) of a right triangle from two inputs.
Ready for the chapter test?
Answer 5 questions. Score 60% or more to mark this chapter complete.
Start the test →💡 Log in to save your progress and earn the certificate.