Java Random Class
In this page:
The Random Class
Random generates pseudo-random numbers from a seed value — two Random instances created with the same seed will produce the exact same sequence of values, which is useful for reproducible tests.
Example: The Random Class
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random r1 = new Random(42);
Random r2 = new Random(42); // same seed
System.out.println(r1.nextInt(100) == r2.nextInt(100)); // true
}
}
Login to try C/C++/Java/PHP code in the editor
Random in a Range
nextInt(bound) restricts output to a range starting at zero; to generate a value within an arbitrary range like 10-20, you typically compute min + random.nextInt(max - min + 1).
Example: Random in a Range
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random random = new Random(1);
int min = 10, max = 20;
int value = min + random.nextInt(max - min + 1);
System.out.println(value >= 10 && value <= 20);
}
}
Login to try C/C++/Java/PHP code in the editor
Seeded Randomness
Explicitly seeding a Random instance (new Random(42)) makes its output sequence deterministic and repeatable, which is valuable for debugging or writing tests that need consistent random values.
Example: Seeded Randomness
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random random = new Random(42); // deterministic sequence
System.out.println(random.nextInt(100));
System.out.println(random.nextInt(100));
}
}
Login to try C/C++/Java/PHP code in the editor
ThreadLocalRandom
ThreadLocalRandom.current() gives each thread its own independent random generator, avoiding the contention that happens when multiple threads share a single Random instance under heavy concurrent use.
Example: ThreadLocalRandom
import java.util.concurrent.ThreadLocalRandom;
public class Main {
public static void main(String[] args) {
int value = ThreadLocalRandom.current().nextInt(1, 10); // own generator per thread
System.out.println(value >= 1 && value < 10);
}
}
Login to try C/C++/Java/PHP code in the editor
Secure Randomness
SecureRandom produces cryptographically strong randomness suitable for security-sensitive uses like generating tokens or keys — regular Random is predictable enough that it should never be used for that purpose.
Example: Secure Randomness
import java.security.SecureRandom;
public class Main {
public static void main(String[] args) {
SecureRandom secureRandom = new SecureRandom(); // cryptographically strong
int token = secureRandom.nextInt(1000000);
System.out.println(token >= 0);
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: