Skip to main content
Java 17 (LTS) · Topic 2 of 2

RandomGenerator API

Definition​

Java 17 added the RandomGenerator interface and a factory with many modern algorithms. You pick an algorithm by name and can seed it, so the same seed always gives the same numbers.

Example code​

A seeded generator gives repeatable numbers

import java.util.random.RandomGenerator;
import java.util.random.RandomGeneratorFactory;

class Demo {
public static void main(String[] args) {
RandomGenerator rng = RandomGeneratorFactory.of("Xoshiro256PlusPlus").create(42L); // seed 42
System.out.println(rng.nextInt(100));
System.out.println(rng.nextInt(100));

RandomGenerator same = RandomGeneratorFactory.of("Xoshiro256PlusPlus").create(42L);
System.out.println(same.nextInt(100)); // same seed, same first number
}
}

// Output:
// 0
// 67
// 0

Finished this page? Track your progress (saved only in your browser).