Java Math.random() Syntax
random() is a static method of the Math class. It takes no arguments and returns a double.
The result is greater than or equal to 0.0 and less than 1.0. On the first call, Math.random() creates one java.util.Random generator and uses it for every later call.
Java Random Number Examples
The following are examples of generating random numbers in Java. Each example runs in the online Java code runner, and the numbers change on every run.
Get a random double between 0 and 1
Math.random() can return 0.0 but never returns 1.0.
Get a random integer between 1 and 10
Multiply the result by 10, cast it to int to get a number from 0 to 9, then add 1.
Get a random integer in a range
For a range from min to max, both included, use min + (int) (Math.random() * (max - min + 1)).
Get a random int with the Random class
The java.util.Random class has nextInt(bound), which returns an int from 0 to bound - 1.