Random Numbers in Java
Our first program will demonstrate how to generate random numbers in Java. Here’s the full source code:
Java’s java.util.Random
class provides pseudorandom number generation.
The nextInt(int bound)
method returns a random int
n, where 0 <= n < bound
.
The nextDouble()
method returns a double
f, where 0.0 <= f < 1.0
.
This can be used to generate random doubles in other ranges, for example 5.0 <= f' < 10.0
.
If you want a known seed, create a new Random
object with a specific seed. This allows for reproducible sequences of random numbers.
To run the program, compile and execute it:
Some of the generated numbers may be different when you run the sample.
See the Random class documentation for references on other random quantities that Java can provide.
For more advanced random number generation, you might want to look into the java.util.concurrent.ThreadLocalRandom
class for better performance in concurrent environments, or the java.security.SecureRandom
class for cryptographically strong random numbers.
Markdown format suitable for Hugo: Yes Explanation adapted to Java: Yes No XML tags: Yes No mention of translation from Go: Yes