The Math Class
The class methods every Java program can use for calculation: absolute value, powers, square roots, and random numbers, with careful attention to their return types and to turning Math.random into a random value in any range.
The Math class is part of the java.lang package, so it is available in every program without an import. It contains only class methods, which are called with the class name: Math.abs, Math.pow, Math.sqrt, and Math.random. Most of them return a double, which affects how results print and where they can be stored. Math.random returns a double from 0.0 up to but not including 1.0, and arithmetic plus casting turns it into a random number in any range you need.
1A Class Made of Class Methods
The Math class contains only class methods. There are no Math objects to create; every method takes what it needs through its parameters and returns a result. Calls always take the form Math.methodName(arguments), and because Math belongs to java.lang, no import statement is required.
Five methods form the core toolbox. abs comes in two overloaded versions, one for int and one for double. pow, sqrt, and random each have a single version, and all three return a double. Knowing each method's parameter types and return type is what lets you predict printed output and avoid compile errors.
Math class contains only class methods. Apart from abs(int), every one of these returns a double.| Method | Parameters | Returns |
|---|---|---|
static int abs(int x) | One int | The absolute value of x, as an int |
static double abs(double x) | One double | The absolute value of x, as a double |
static double pow(double base, double exponent) | Two doubles | base raised to the power exponent |
static double sqrt(double x) | One double (non-negative) | The non-negative square root of x |
static double random() | None | A double from 0.0 up to but not including 1.0 |
Math m = new Math(); does not compile. The Math class is used only through its class methods: write Math.sqrt(25), never m.sqrt(25).
2Absolute Value
The absolute value of a number is its distance from zero: −7 and 7 both have absolute value 7. Math.abs(int x) returns an int, and Math.abs(double x) returns a double. Java picks the version that matches the argument, so Math.abs(-7) prints 7 while Math.abs(-7.0) prints 7.0.
Absolute value is the natural tool for measuring how far apart two values are regardless of order. The difference between a guess and a target, Math.abs(guess - target), is the same whether the guess was too high or too low, which makes it ideal for comparisons such as "within 5 of the target."
Absolute Value for int and double
Predict each result and notice its type.
System.out.println(Math.abs(-7));
System.out.println(Math.abs(-7.25));
System.out.println(Math.abs(3 - 8));
System.out.println(Math.abs(12));
7
7.25
5
12
- 1
Math.abs(-7). Theintversion runs and returns theint7. - 2
Math.abs(-7.25). Thedoubleversion returns 7.25. - 3
Math.abs(3 - 8). The argument is evaluated first: −5, so the result is 5. - 4
Math.abs(12). A non-negative value is returned unchanged.
Math.abs is overloaded: the int version returns an int and the double version returns a double.3Powers and Square Roots
Math.pow(double base, double exponent) returns the value of the first parameter raised to the power of the second. Math.sqrt(double x) returns the non-negative square root of its argument. Both take double parameters, so int arguments are widened automatically, and both return a double, so even whole-number answers print with a decimal point: Math.pow(2, 3) is 8.0 and Math.sqrt(49) is 7.0.
Exponents can be zero, negative, or fractional: Math.pow(5, 0) is 1.0, Math.pow(2, -1) is 0.5, and Math.pow(9, 0.5) is 3.0. Results that are irrational, such as Math.sqrt(2), are approximations stored in a double, so they carry the usual round-off. Math calls can be nested, with inner calls evaluated first, which makes formulas such as the Pythagorean theorem a single line of code.
Math.pow and Math.sqrt always return a double, even when the answer is a whole number.Powers and Square Roots
Predict each output.
System.out.println(Math.pow(2, 10));
System.out.println(Math.pow(5, 0));
System.out.println(Math.pow(2, -1));
System.out.println(Math.sqrt(144));
System.out.println(Math.sqrt(2));
1024.0
1.0
0.5
12.0
1.4142135623730951
- 1
Math.pow(2, 10). 2 to the 10th power is 1024, returned as thedouble1024.0. - 2
Math.pow(5, 0). Any nonzero base to the power 0 is 1, so 1.0. - 3
Math.pow(2, -1). A negative exponent means a reciprocal: 1/2 = 0.5. - 4
Math.sqrt(144). 12.0, adoubleeven though the root is whole. - 5
Math.sqrt(2). An irrational root is approximated to about 16 significant digits.
pow and sqrt always return a double.The Length of a Diagonal
A rectangular garden bed is 5 m by 12 m. Use the Pythagorean theorem, c = √(a² + b²), to compute the diagonal.
double a = 5;
double b = 12;
double diagonal = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
System.out.println(diagonal);
13.0
- 1Inner calls first.
Math.pow(a, 2)is 25.0 andMath.pow(b, 2)is 144.0. - 2Add. 25.0 + 144.0 = 169.0.
- 3Square root.
Math.sqrt(169.0)is 13.0. - 4Alternative.
a * a + b * bworks just as well for squaring;Math.powis most useful for exponents other than 2.
Storing a pow Result in an int
Why does this fail, and how can it be fixed?
int side = 4;
int area = Math.pow(side, 2);
System.out.println(area);
int side = 4;
int area = (int) Math.pow(side, 2);
System.out.println(area);
16
- 1The return type is
double.Math.pow(4, 2)returns 16.0. - 2Narrowing needs a cast. Storing a
doublein anintcould lose information, so Java refuses: "possible lossy conversion from double to int." - 3The fix. Cast the result with
(int), or store it in adoublevariable. For simple squares,side * sidekeeps everything asintwith no cast needed.
Math.pow and Math.sqrt return double values. int x = Math.sqrt(16); does not compile, and System.out.println(Math.pow(3, 2)); prints 9.0, not 9. Store the result in a double, or cast it explicitly when a whole number is guaranteed.
4Math.random
Math.random() takes no arguments and returns a double value greater than or equal to 0.0 and less than 1.0. The lower end, 0.0, is a possible result; the upper end, 1.0, is never returned. Each call produces a new value, so a program that uses Math.random can behave differently every time it runs.
Random numbers let programs simulate chance events such as coin flips, dice, and shuffled cards, and they make games and simulations unpredictable. The raw value is rarely useful by itself, but it is the starting point for every random value you will build: scaling, casting, and shifting transform the interval [0.0, 1.0) into whatever range a program needs.
Math.random() returns a double that is greater than or equal to 0.0 and less than 1.0.5Random Values in a Defined Range
The values returned from Math.random can be manipulated using arithmetic and casting operators to produce a random int or double in a defined range. For integers, follow three steps. Scale: multiply by the number of possible values, giving a double from 0.0 up to that number. Truncate: cast to int, giving the whole numbers from 0 up to one less than that number. Shift: add the smallest value you want.
For integers from min to max inclusive, there are max - min + 1 possible values, so the general form is (int) (Math.random() * (max - min + 1)) + min. For a random double in a range, skip the cast: Math.random() * width + start gives values from start up to but not including start + width. To check any expression, substitute the smallest and largest possible values of Math.random() and evaluate.
int in a defined range: scale, truncate, then shift.| Goal (inclusive) | Number of values | Expression |
|---|---|---|
| 1 to 6 | 6 | (int) (Math.random() * 6) + 1 |
| 0 to 9 | 10 | (int) (Math.random() * 10) |
| 10 to 20 | 11 | (int) (Math.random() * 11) + 10 |
| −5 to 5 | 11 | (int) (Math.random() * 11) - 5 |
| min to max | max − min + 1 | (int) (Math.random() * (max - min + 1)) + min |
Checking the Range of a Random Expression
The expression (int) (Math.random() * 6) + 1 simulates a die. Check its smallest and largest possible values by substituting the smallest and largest values Math.random() can return (0.0, and the largest double below 1.0, which is 0.9999999999999999).
double low = 0.0;
double high = 0.9999999999999999;
System.out.println((int) (low * 6) + 1);
System.out.println((int) (high * 6) + 1);
1
6
- 1Smallest. 0.0 × 6 = 0.0; cast gives 0; plus 1 gives 1.
- 2Largest. Just below 1.0 times 6 is just below 6.0; the cast truncates to 5; plus 1 gives 6.
- 3Every value between. The scaled value lands in one of six equal-width slices, [0, 1), [1, 2), …, [5, 6), so each of 1 through 6 is equally likely.
Writing Expressions for Given Ranges
Write an expression that produces a random int in each range, inclusive.
- 0 to 9
- 10 to 20
- −5 to 5
- A random
doublefrom 2.0 up to but not including 7.0
- 1The pattern. For integers from
mintomaxinclusive, there aremax - min + 1possible values:(int) (Math.random() * (max - min + 1)) + min. - 20 to 9. 10 values starting at 0:
(int) (Math.random() * 10). - 310 to 20. 11 values starting at 10:
(int) (Math.random() * 11) + 10. - 4−5 to 5. 11 values starting at −5:
(int) (Math.random() * 11) - 5. - 5A double from 2.0 to 7.0. No cast: the width is 5.0 and the start is 2.0, so
Math.random() * 5 + 2.
double range, multiply by the width and add the start, with no cast.A Random Coin and Die
Each run of this program prints different values. Which values are possible on each line?
int coin = (int) (Math.random() * 2);
int die = (int) (Math.random() * 6) + 1;
double angle = Math.random() * 360;
System.out.println(coin);
System.out.println(die);
System.out.println(angle);
Output varies from run to run; one run might print 1, then 4, then 217.48390125591034.
- 1
coin.Math.random() * 2is from 0.0 to just below 2.0; the cast gives 0 or 1. - 2
die. 1 through 6, as checked in the previous example. - 3
angle. Adoublefrom 0.0 up to but not including 360.0, with no cast, so it has a fractional part.
coin is 0 or 1, die is 1 to 6, and angle is a double in [0.0, 360.0). Each call to Math.random() produces a new value.To include both 1 and 10, the multiplier must be 10, the number of values, not 9 (which would give 1 to 9) or 11 (which would give 1 to 11). Count the values with max - min + 1, and check the extremes before trusting the expression.
6Common Errors With Math Methods
Most Math mistakes involve types or parentheses. A cast applies only to the value immediately after it, so (int) Math.random() * 10 casts the random value first, which always gives 0, and the result is always 0. The parentheses in (int) (Math.random() * 10) make the cast apply after scaling, which is what you want.
Other frequent problems: storing a double result in an int without a cast, forgetting that Math.pow takes the base first and the exponent second, and expecting Math.random() to reach 1.0. Reading each method's signature and return type before using it prevents nearly all of them.
| Expression | Possible results | Why |
|---|---|---|
Math.random() * 10 | double from 0.0 to just below 10.0 | Scales the range; no cast, so fractions remain |
(int) Math.random() * 10 | Always 0 | The cast applies to Math.random() first, giving 0, then 0 × 10 |
(int) (Math.random() * 10) | 0 to 9 | Parentheses make the cast apply after scaling |
(int) (Math.random() * 10) + 1 | 1 to 10 | Shift by the smallest value |
(int) Math.random() * 6 + 1 always evaluates to 1, because (int) Math.random() is always 0. Put parentheses around the multiplication so the cast happens after scaling: (int) (Math.random() * 6) + 1.
Four Habits for the Math Class
1. Call Through the Class
Math.abs, Math.pow, Math.sqrt, Math.random; no objects, no import.
2. Check the Return Type
Only abs(int) returns an int; the rest return double.
3. Count, Then Shift
Multiply by max − min + 1, cast, then add min.
4. Test the Extremes
Substitute 0.0 and just under 1.0 to check a random range.
The Math class is part of the java.lang package and contains only class methods. Math.abs(int) returns an int absolute value and Math.abs(double) a double one; Math.pow(double, double) returns the first parameter raised to the power of the second; Math.sqrt(double) returns the non-negative square root; and Math.random() returns a double greater than or equal to 0.0 and less than 1.0. The values returned from Math.random can be manipulated using arithmetic and casting operators to produce a random int or double in a defined range.