Math.random()
Returns a random decimal number from 0 (inclusive) to 1 (exclusive).
Available since: Java 1.0
Syntax
static double random()Return value
doubleA random double in the range [0, 1).
Examples
A random integer from 1 to 6 — a dice roll. The result differs on every run:
void main() {
int dice = (int) (Math.random() * 6) + 1;
IO.println(dice);
}Output:
2Notes
The formula for an integer from min to max inclusive is (int) (Math.random() * (max - min + 1)) + min. Clearer options are ThreadLocalRandom.current().nextInt(min, max + 1) or new Random().nextInt().
See also
- Random — A random number generator: integers in a range, decimals, booleans.
- ThreadLocalRandom — A ready random number generator that you do not need to create; fast in multithreaded code too.
Related recipes
In the tutorial
- Operators — Java arithmetic operators, integer division and remainder, compound assignment, increment, comparison and logical operators.