Java Program to Generate Random Number
Random rand = new Random(); int num = rand.nextInt(); which gives a random integer, or use rand.nextInt(bound) for a number within a range.Examples
How to Think About It
Algorithm
Code
import java.util.Random; public class RandomNumberExample { public static void main(String[] args) { Random rand = new Random(); int randomNum = rand.nextInt(100); // random number between 0 and 99 System.out.println("Random number between 0 and 99: " + randomNum); } }
Dry Run
Let's trace generating a random number between 0 and 99 through the code
Create Random object
Random rand = new Random(); // rand is ready to generate numbers
Generate random number
int randomNum = rand.nextInt(100); // randomNum gets a value like 42
Print the number
System.out.println("Random number between 0 and 99: " + randomNum); // prints the number
| Step | Variable | Value |
|---|---|---|
| 1 | rand | Random object created |
| 2 | randomNum | 42 |
| 3 | Output | Random number between 0 and 99: 42 |
Why This Works
Step 1: Create Random object
The Random class provides methods to generate random numbers. Creating an object prepares it to produce random values.
Step 2: Generate random number within range
Calling nextInt(100) returns a random integer from 0 up to 99, simulating picking a number from a set range.
Step 3: Print the result
The program prints the random number so you can see the output on the screen.
Alternative Approaches
public class RandomNumberMath { public static void main(String[] args) { int randomNum = (int)(Math.random() * 100); System.out.println("Random number between 0 and 99: " + randomNum); } }
import java.util.concurrent.ThreadLocalRandom; public class RandomNumberThreadLocal { public static void main(String[] args) { int randomNum = ThreadLocalRandom.current().nextInt(100); System.out.println("Random number between 0 and 99: " + randomNum); } }
Complexity: O(1) time, O(1) space
Time Complexity
Generating a random number is a constant time operation because it does not depend on input size or loops.
Space Complexity
Only a small fixed amount of memory is used for the Random object and the integer variable.
Which Approach is Fastest?
Using ThreadLocalRandom can be faster in multithreaded environments, while Math.random() is simpler but less flexible.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Random class | O(1) | O(1) | General purpose random numbers |
| Math.random() | O(1) | O(1) | Simple random numbers without extra imports |
| ThreadLocalRandom | O(1) | O(1) | Multithreaded applications |
nextInt(bound) to get a random number within a specific range starting from zero.nextInt(bound) excludes the upper bound, so the max number is one less than the bound.