Java Random Methods
All Random Methods
The Random class creates random numbers (numbers that you cannot know before the program runs). Import java.util.Random, create a Random object with Random rand = new Random();, and call the methods on the object, for example rand.nextInt(6).
Use Random instead of Math.random() when you need something other than a double from 0.0 to 1.0, for example a whole number in a range or a boolean. With a seed (a start value), a Random object can also give the same numbers each time the program runs, which is useful for testing.
| Method | Description | Return Type |
|---|---|---|
| ints() | Returns a stream of random int values, for example 5 numbers from 1 to 6 | IntStream |
| nextBoolean() | Returns a random boolean value, true or false | boolean |
| nextDouble() | Returns a random double from 0.0 up to (but not including) 1.0 | double |
| nextFloat() | Returns a random float from 0.0 up to (but not including) 1.0 | float |
| nextGaussian() | Returns a random double from a normal distribution (a bell curve), with an average of 0.0 | double |
| nextInt() | Returns a random int, or a random int from 0 up to (but not including) a given bound | int |
| nextLong() | Returns a random long value, which can be positive or negative | long |
| setSeed() | Sets the seed (the start value) of the Random object. The same seed always gives the same numbers | void |
Related Pages
Java How To Generate Random Numbers