← Back to Core Java Course | Chapter 13: Advanced Topics & Reference | Lesson 3 of 10

Java Random Class

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

java
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
	}
}

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

java
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);
	}
}

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

java
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));
	}
}

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

java
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);
	}
}

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

java
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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.