Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to generate a random number

Short answer

nextInt(from, to) returns a random integer from from inclusive to to exclusive:

void main() {
    var random = new Random();
    int dice = random.nextInt(1, 7);
 
    IO.println(dice);
}

Output:

1

This gives a number from 1 to 6, and every run gives a new value.

A decimal number

nextDouble() returns a number from 0 to 1, and the two-argument version gives one from your range:

void main() {
    var random = new Random();
 
    IO.println(random.nextDouble());
    IO.println(random.nextDouble(10.0, 20.0));
}

Output:

0.7441592756923616
16.647522933450976

A repeatable sequence

If you pass a seed to Random, the sequence is the same on every run. This is handy in tests:

void main() {
    var random = new Random(42);
    for (int i = 0; i < 5; i++) {
        IO.print(random.nextInt(100) + " ");
    }
    IO.println();
}

Output:

30 63 48 84 70

Many numbers at once

ints() returns a stream of random numbers:

void main() {
    List<Integer> numbers = new Random(7).ints(5, 1, 50).boxed().toList();
    IO.println(numbers);
}

Output:

[46, 41, 40, 45, 20]

Common mistake

Creating a new Random in a loop or forgetting that the upper bound is exclusive. nextInt(6) never returns 6 — only numbers from 0 to 5. For passwords and tokens use SecureRandom, and in multithreaded code ThreadLocalRandom.current().

Functions used in this recipe

  • 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.
  • Math.random() — Returns a random decimal number from 0 (inclusive) to 1 (exclusive).

Thanks for reading!

Donate to the site — we work hard for you.