πŸ” Java How-To Examples
Estimated reading: 3 minutes 30 views

🎲 Java Program to Generate Random Number – With Examples & Methods

🧲 Introduction

Random numbers play a key role in gaming, simulations, security, and testing applications. In Java, generating a random number is easy using built-in classes like Math, Random, and ThreadLocalRandom.

By the end of this article, you’ll learn how to:

  • βœ… Generate random integers and decimals
  • βœ… Use Math.random(), Random, and ThreadLocalRandom
  • βœ… Set ranges and apply best practices

πŸ”’ 1. Using Math.random() – Simple & Quick

public class RandomMath {
    public static void main(String[] args) {
        double randomValue = Math.random(); // 0.0 <= value < 1.0
        System.out.println("Random number (0–1): " + randomValue);

        int randomInt = (int) (Math.random() * 100); // 0 to 99
        System.out.println("Random integer (0–99): " + randomInt);
    }
}

βœ… Explanation:

  • Math.random() generates a double from 0.0 to less than 1.0.
  • Multiply and cast to get a specific integer range.

πŸ’‘ Best for quick, lightweight randomness.


🎲 2. Using java.util.Random – More Control

import java.util.Random;

public class RandomWithClass {
    public static void main(String[] args) {
        Random rand = new Random();

        int randInt = rand.nextInt(100);       // 0–99
        double randDouble = rand.nextDouble(); // 0.0–1.0

        System.out.println("Random integer (0–99): " + randInt);
        System.out.println("Random double (0–1): " + randDouble);
    }
}

βœ… Explanation:

  • nextInt(bound) gives you a range [0, bound).
  • nextDouble() gives 0.0 ≀ value < 1.0.

πŸ’‘ Use this when you need repeatable or seedable randomness.


⚑ 3. Using ThreadLocalRandom – Recommended for Multi-Threading

import java.util.concurrent.ThreadLocalRandom;

public class ThreadLocalRandomExample {
    public static void main(String[] args) {
        int randomInt = ThreadLocalRandom.current().nextInt(50, 101); // 50 to 100
        double randomDouble = ThreadLocalRandom.current().nextDouble(1.5, 3.5);

        System.out.println("Random int (50–100): " + randomInt);
        System.out.println("Random double (1.5–3.5): " + randomDouble);
    }
}

βœ… Explanation:

  • Supports inclusive lower and exclusive upper bounds.
  • Safe and efficient in multi-threaded applications.

πŸ“‹ Comparison Table – Random Generation in Java

MethodTypeThread Safe?Range ControlUse Case
Math.random()doubleβœ… Yes❌ ManualQuick one-liners
new Random()int, double❌ Noβœ… YesGeneral-purpose, seedable
ThreadLocalRandomint, doubleβœ… Yesβœ… YesHigh-performance, multi-thread

πŸ§ͺ Generate Random Boolean or Float

Random rand = new Random();

boolean randBool = rand.nextBoolean();
float randFloat = rand.nextFloat(); // 0.0 – 1.0

System.out.println("Random boolean: " + randBool);
System.out.println("Random float: " + randFloat);

βœ… Works with all primitive types.


πŸ“Œ Summary

You’ve now mastered:

  • βœ… Generating random numbers using Math.random(), Random, and ThreadLocalRandom
  • βœ… Controlling ranges and types (int, double, boolean)
  • βœ… Writing clean and safe randomization code

Random numbers are a core tool for games, security, simulations, and even AI.


❓ FAQ – Java Random Number Generation

❓How to generate a random number between 1 and 10?

int randNum = ThreadLocalRandom.current().nextInt(1, 11);

βœ… Generates values from 1 to 10 (upper bound is exclusive).


❓Can I generate the same random sequence every time?

Yes, by setting a seed:

Random seededRand = new Random(42); // fixed seed
System.out.println(seededRand.nextInt(100));

❓Which method is best for performance?

ThreadLocalRandom is best for multi-threaded or high-frequency random generation.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Random Number

Or Copy Link

CONTENTS
Scroll to Top