Java Random Number

Generate random numbers for games, simulations, and testing

🎲 What are Random Numbers?

Random numbers are unpredictable values used in games, simulations, and security. Java provides multiple ways to generate random numbers using Math.random() and Random class for different needs.


// Simple random number generation
import java.util.Random;

public class RandomNumber {
    public static void main(String[] args) {
        // Using Math.random()
        double randomDouble = Math.random();
        int randomInt = (int)(Math.random() * 100) + 1; // 1-100
        
        // Using Random class
        Random rand = new Random();
        int randomNumber = rand.nextInt(100) + 1; // 1-100
        
        System.out.println("Random double: " + randomDouble);
        System.out.println("Random int (Math): " + randomInt);
        System.out.println("Random int (Random): " + randomNumber);
    }
}
                                    

Output:

Random double: 0.7234567891234567
Random int (Math): 42
Random int (Random): 73

Random Generation Methods

📊

Math.random()

Simple method returning 0.0 to 1.0

// Random double between 0.0 and 1.0
double random = Math.random();

// Random int between 1 and 100
int randomInt = (int)(Math.random() * 100) + 1;
🎯

Random Class

More control and different data types

Random rand = new Random();
int randomInt = rand.nextInt(100); // 0-99
boolean randomBool = rand.nextBoolean();
double randomDouble = rand.nextDouble();
🎮

Range Control

Generate numbers in specific ranges

// Random between min and max (inclusive)
static int randomRange(int min, int max) {
    return (int)(Math.random() * (max - min + 1)) + min;
}
🌱

Seeded Random

Reproducible random sequences

// Same seed = same sequence
Random rand = new Random(12345);
int first = rand.nextInt(100);
int second = rand.nextInt(100);

🔹 Complete Random Number Program

Here's a comprehensive program demonstrating various random number techniques:

import java.util.*;

public class RandomComplete {
    public static void main(String[] args) {
        System.out.println("=== Random Number Examples ===\n");
        
        // Basic Math.random()
        System.out.println("1. Basic Math.random():");
        for (int i = 0; i < 5; i++) {
            System.out.println("Random double: " + Math.random());
        }
        
        // Random integers in range
        System.out.println("\n2. Random integers (1-10):");
        for (int i = 0; i < 5; i++) {
            int random = (int)(Math.random() * 10) + 1;
            System.out.println("Random int: " + random);
        }
        
        // Using Random class
        System.out.println("\n3. Using Random class:");
        Random rand = new Random();
        System.out.println("Random int (0-99): " + rand.nextInt(100));
        System.out.println("Random boolean: " + rand.nextBoolean());
        System.out.println("Random double: " + rand.nextDouble());
        System.out.println("Random float: " + rand.nextFloat());
        
        // Custom range method
        System.out.println("\n4. Custom range (50-150):");
        for (int i = 0; i < 5; i++) {
            System.out.println("Random: " + randomInRange(50, 150));
        }
        
        // Random array elements
        System.out.println("\n5. Random array elements:");
        String[] colors = {"Red", "Blue", "Green", "Yellow", "Purple"};
        for (int i = 0; i < 3; i++) {
            System.out.println("Random color: " + getRandomElement(colors));
        }
        
        // Dice simulation
        System.out.println("\n6. Dice Roll Simulation:");
        simulateDiceRolls(10);
        
        // Random password generation
        System.out.println("\n7. Random Password:");
        System.out.println("Password: " + generateRandomPassword(8));
    }
    
    // Generate random number in range (inclusive)
    static int randomInRange(int min, int max) {
        return (int)(Math.random() * (max - min + 1)) + min;
    }
    
    // Get random element from array
    static String getRandomElement(String[] array) {
        int randomIndex = (int)(Math.random() * array.length);
        return array[randomIndex];
    }
    
    // Simulate dice rolls
    static void simulateDiceRolls(int rolls) {
        int[] counts = new int[7]; // Index 1-6 for dice faces
        
        for (int i = 0; i < rolls; i++) {
            int roll = (int)(Math.random() * 6) + 1;
            counts[roll]++;
            System.out.print(roll + " ");
        }
        
        System.out.println("\nDice frequency:");
        for (int i = 1; i <= 6; i++) {
            System.out.println("Face " + i + ": " + counts[i] + " times");
        }
    }
    
    // Generate random password
    static String generateRandomPassword(int length) {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder password = new StringBuilder();
        
        for (int i = 0; i < length; i++) {
            int randomIndex = (int)(Math.random() * chars.length());
            password.append(chars.charAt(randomIndex));
        }
        
        return password.toString();
    }
}

Output:

=== Random Number Examples ===

1. Basic Math.random():
Random double: 0.7234567891234567
Random double: 0.1234567891234567

2. Random integers (1-10):
Random int: 7
Random int: 3

3. Using Random class:
Random int (0-99): 42
Random boolean: true

7. Random Password:
Password: aB3xY9mK

🧠 Test Your Knowledge

What does Math.random() return?