1.11 - Math Class
The
Math class lives in the java.lang package, and everything in java.lang is available automatically, no import needed. Every method in Math is a class method (static).Here are the ones on the AP Java Quick Reference:
static int abs(int x) // absolute value of an int static double abs(double x) // absolute value of a double static double pow(double base, double exponent) // base raised to exponent static double sqrt(double x) // non-negative square root static double random() // random double, 0.0 <= x < 1.0
A few details that show up on the exam:
Math.absis overloaded. Give it anintand you get anintback, give it adoubleand you get adoubleback.Math.abs(-7)is7, butMath.abs(-7.5)is7.5.
Math.powandMath.sqrtalways return adouble, even when the answer is a whole number.Math.pow(2, 3)is8.0andMath.sqrt(16)is4.0.
- Because of that,
int x = Math.pow(2, 3);won’t compile. You need a cast:int x = (int) Math.pow(2, 3);stores 8.
Math calls can go inside bigger expressions, even inside other Math calls. For a right triangle with legs 3 and 4:double a = 3; double b = 4; double hyp = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2)); // Math.sqrt(9.0 + 16.0) = 5.0
Example usage:
int a = Math.abs(-7); // 7 double p = Math.pow(2, 3); // 8.0 double s = Math.sqrt(16.0); // 4.0 double r = Math.random(); // some value like 0.372
You can manipulate
Math.random() with arithmetic and casting to get a random int or double within a specific range. Just keep track of whether each endpoint is inclusive (included) or exclusive (not included).// random int from 0 to 9 (inclusive) int randomNum = (int)(Math.random() * 10); // random int from 1 to 6 (inclusive), like a die roll int diceRoll = (int)(Math.random() * 6) + 1;
Here’s how the dice roll works, one step at a time:
Math.random()gives adoublefrom0.0up to, but not including,1.0.
- Multiplying by 6 stretches that to a
doublefrom0.0up to, but not including,6.0.
- Casting to
inttruncates it to 0, 1, 2, 3, 4, or 5.
- Adding 1 shifts it to 1, 2, 3, 4, 5, or 6.
In general, to get a random
int from min to max (both inclusive), multiply by how many values are possible and add the smallest one:int n = (int) (Math.random() * (max - min + 1)) + min; // random int from 5 to 15 inclusive (11 possible values) int r = (int) (Math.random() * 11) + 5;
For a random
double, skip the cast. Math.random() * 5 + 10 gives a double from 10.0 (inclusive) up to 15.0 (exclusive).Careful with parentheses:
(int) Math.random() * 6 is always 0. The cast happens first, and since Math.random() is less than 1.0, it truncates to 0. Then 0 times 6 is 0.