Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Random

A random number generator: integers in a range, decimals, booleans.

Available since: Java 1.0

Syntax

public class Random implements RandomGenerator

Examples

With a fixed seed the sequence is always the same — handy for tests:

void main() {
    var random = new Random(42);
    IO.println(random.nextInt(100));
    IO.println(random.nextInt(1, 7));
    IO.println(random.nextBoolean());
}

Output:

30
4
true

Without a seed every run gives different numbers — for example, a random list element:

void main() {
    List<String> colors = List.of("red", "green", "blue");
    var random = new Random();
    IO.println(colors.get(random.nextInt(colors.size())));
}

Output:

green

Notes

nextInt(bound) returns a number from 0 to bound - 1, and nextInt(origin, bound) (Java 17) from origin to bound - 1. The output of the second example is random. Random is not suitable for passwords and tokens — use SecureRandom. To shuffle a list use Collections.shuffle(list).

See also

  • ThreadLocalRandom — A ready random number generator that you do not need to create; fast in multithreaded code too.
  • Math.random() — Returns a random decimal number from 0 (inclusive) to 1 (exclusive).

Related recipes

In the tutorial

  • Operators — Java arithmetic operators, integer division and remainder, compound assignment, increment, comparison and logical operators.

Thanks for reading!

Donate to the site — we work hard for you.