Generating random numbers is a common requirement in Java programming. Developers use random values when building games, selecting items, creating test data, shuffling content, generating verification codes, and simulating unpredictable events.

Java provides several ways to generate random numbers. The most common options include the Random class, the Math.random() method, ThreadLocalRandom, SecureRandom, and the modern RandomGenerator interface.

The correct method depends on what you are building. A simple console application may only need Random or Math.random(). A multithreaded application may perform better with ThreadLocalRandom, while passwords, tokens, and security codes require SecureRandom.

This guide explains how to get random number in Java using each method, along with practical examples, range calculations, common mistakes, and recommendations for choosing the right generator.

Quick Answer: How Do You Generate a Random Number in Java?

The easiest beginner-friendly method is to use the Random class:

import java.util.Random;

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

        int randomNumber = random.nextInt(100);

        System.out.println(randomNumber);
    }
}

The program generates an integer between 0 and 99.

The number 100 is the exclusive upper limit. This means Java may return 0, but it will never return 100. Oracle’s Java documentation defines nextInt(bound) as returning a pseudorandom integer from zero inclusive to the specified bound exclusive.

How to Get Random Number in Java Using the Random Class

The java.util.Random class is one of the most widely recognized ways to generate pseudorandom values in Java.

You must import the class, create an object, and call one of its available methods.

import java.util.Random;

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

        int number = random.nextInt();

        System.out.println("Random number: " + number);
    }
}

Calling nextInt() without a bound can return any valid Java int, including positive and negative values.

If you only want a positive number within a limited range, provide a positive bound:

Random random = new Random();

int number = random.nextInt(10);

System.out.println(number);

The possible results are:

0, 1, 2, 3, 4, 5, 6, 7, 8, or 9

Generate a Random Number Between 1 and 10

To generate a number from 1 through 10, add one to the result:

import java.util.Random;

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

        int number = random.nextInt(10) + 1;

        System.out.println(number);
    }
}

Here is how the expression works:

random.nextInt(10)

This part produces a number between 0 and 9.

Adding one changes the possible range to 1 through 10:

random.nextInt(10) + 1

Generate a Random Number Between Two Values

Suppose you want a random integer between a minimum and maximum value, including both limits.

Use this formula:

random.nextInt(max - min + 1) + min

Example:

import java.util.Random;

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

        int min = 20;
        int max = 50;

        int number = random.nextInt(max - min + 1) + min;

        System.out.println("Random number: " + number);
    }
}

This program can return any integer from 20 to 50, including both 20 and 50.

The +1 is important because the upper bound supplied to nextInt() is excluded. Without it, the maximum value would never be selected.

How to Generate a Random Number Using Math.random()

The Math.random() method is another simple way to generate random values in Java.

It does not require you to import or create a separate object.

public class Main {
    public static void main(String[] args) {
        double number = Math.random();

        System.out.println(number);
    }
}

Math.random() returns a double value greater than or equal to 0.0 and less than 1.0.

Possible results might look like:

0.245718
0.819362
0.003154

Java uses an internally managed pseudorandom number generator for calls to Math.random().

Generate an Integer With Math.random()

You can multiply the result and convert it to an integer:

public class Main {
    public static void main(String[] args) {
        int number = (int) (Math.random() * 100);

        System.out.println(number);
    }
}

This code generates an integer between 0 and 99.

The cast to int removes the decimal portion of the number.

For example:

Math.random() returns 0.5834
0.5834 × 100 becomes 58.34
Casting to int produces 58

Generate a Number Between a Minimum and Maximum

Use this formula when both limits should be included:

(int) (Math.random() * (max - min + 1)) + min

Example:

public class Main {
    public static void main(String[] args) {
        int min = 5;
        int max = 15;

        int number = (int) (Math.random() * (max - min + 1)) + min;

        System.out.println(number);
    }
}

The possible results range from 5 through 15.

Math.random() is convenient for small programs, demonstrations, and basic calculations. However, a dedicated random generator is usually clearer when an application needs to create many values or use multiple data types.

Random vs Math.random in Java

Both approaches can generate pseudorandom values, but they are used differently.

The Random class gives you methods for generating integers, doubles, floats, longs, Boolean values, and streams of values. Math.random() directly returns only a double.

Use Math.random() when you need a quick decimal number or a simple one-line expression.

Use the Random class when you need greater control, reusable generator objects, repeatable seeds, or several types of random values.

Example using multiple Random methods:

import java.util.Random;

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

        int randomInt = random.nextInt(100);
        long randomLong = random.nextLong();
        double randomDouble = random.nextDouble();
        float randomFloat = random.nextFloat();
        boolean randomBoolean = random.nextBoolean();

        System.out.println("Integer: " + randomInt);
        System.out.println("Long: " + randomLong);
        System.out.println("Double: " + randomDouble);
        System.out.println("Float: " + randomFloat);
        System.out.println("Boolean: " + randomBoolean);
    }
}

How to Use ThreadLocalRandom in Java

ThreadLocalRandom is designed for applications where multiple threads generate random numbers.

Instead of making several threads compete for access to one shared generator, it provides a generator associated with the current thread. Oracle recommends it for concurrent programs because it can reduce contention and overhead compared with sharing a Random object.

Example:

import java.util.concurrent.ThreadLocalRandom;

public class Main {
    public static void main(String[] args) {
        int number = ThreadLocalRandom.current().nextInt(100);

        System.out.println(number);
    }
}

This generates a value between 0 and 99.

Generate a Number Within a Range

ThreadLocalRandom provides a convenient method that accepts an origin and a bound:

import java.util.concurrent.ThreadLocalRandom;

public class Main {
    public static void main(String[] args) {
        int number = ThreadLocalRandom.current().nextInt(10, 21);

        System.out.println(number);
    }
}

The first value is inclusive, while the second value is exclusive.

Therefore:

nextInt(10, 21)

returns a number from 10 through 20.

The origin-inclusive and bound-exclusive behavior is documented in the Java API.

When Should You Use ThreadLocalRandom?

Consider using it when:

  • Your application performs concurrent tasks.
  • Multiple threads frequently request random values.
  • You do not need to manually control the generator’s seed.
  • You want a direct origin-and-bound method.

For a basic single-threaded beginner project, Random is still perfectly understandable. For concurrent systems, ThreadLocalRandom is often the more suitable choice.

How to Get a Secure Random Number in Java

Normal pseudorandom generators are not appropriate for sensitive security operations.

For passwords, authentication tokens, reset links, cryptographic keys, one-time codes, and similar security-related values, use SecureRandom.

Oracle describes SecureRandom as a cryptographically strong random number generator designed to produce nondeterministic output suitable for security-sensitive uses.

Example:

import java.security.SecureRandom;

public class Main {
    public static void main(String[] args) {
        SecureRandom secureRandom = new SecureRandom();

        int number = secureRandom.nextInt(100);

        System.out.println(number);
    }
}

This generates a secure random integer between 0 and 99.

Generate a Six-Digit Verification Code

A six-digit code must begin at 100000 and end at 999999.

import java.security.SecureRandom;

public class VerificationCode {
    public static void main(String[] args) {
        SecureRandom secureRandom = new SecureRandom();

        int code = secureRandom.nextInt(900000) + 100000;

        System.out.println("Verification code: " + code);
    }
}

Why is the bound 900000?

The range contains 900,000 possible values:

100000 through 999999

The generator first produces a value from 0 through 899999. Adding 100000 shifts the result into the required six-digit range.

A real authentication system should also enforce expiration, limit attempts, protect stored codes, and prevent repeated submissions. Random number generation is only one part of a secure verification process.

How to Use RandomGenerator in Modern Java

Java 17 introduced the java.util.random.RandomGenerator interface as a common API for random number generators. It supports methods for integers, longs, doubles, Boolean values, and streams.

Example:

import java.util.random.RandomGenerator;

public class Main {
    public static void main(String[] args) {
        RandomGenerator generator = RandomGenerator.getDefault();

        int number = generator.nextInt(1, 101);

        System.out.println(number);
    }
}

This generates an integer from 1 through 100.

The lower limit is included, and the upper limit is excluded.

Developers can also request a generator by algorithm name:

import java.util.random.RandomGenerator;

public class Main {
    public static void main(String[] args) {
        RandomGenerator generator =
                RandomGenerator.of("L64X128MixRandom");

        int number = generator.nextInt(1, 101);

        System.out.println(number);
    }
}

The modern API is useful when you want a consistent interface and the flexibility to select among supported random-generation algorithms.

For code that must run on Java 8 or Java 11, use Random, ThreadLocalRandom, or SecureRandom instead.

How to Generate Random Double Values

Use nextDouble() to produce a decimal value:

import java.util.Random;

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

        double number = random.nextDouble();

        System.out.println(number);
    }
}

The result is greater than or equal to 0.0 and less than 1.0.

To generate a double within another range, use:

double number = min + (max - min) * random.nextDouble();

Example:

import java.util.Random;

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

        double min = 10.0;
        double max = 50.0;

        double number = min + (max - min) * random.nextDouble();

        System.out.println(number);
    }
}

This produces a decimal value starting at 10.0 and remaining below 50.0.

To display a limited number of decimal places:

System.out.printf("%.2f%n", number);

This formats the result to two decimal places without changing the underlying random-generation process.

How to Generate Multiple Random Numbers

A loop can generate several random values:

import java.util.Random;

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

        for (int i = 0; i < 5; i++) {
            int number = random.nextInt(100) + 1;
            System.out.println(number);
        }
    }
}

This prints five random numbers between 1 and 100.

Create the Random object before the loop. Reusing one generator is cleaner than repeatedly creating a new object inside every iteration.

Generate Random Numbers With a Stream

The Random class can also create streams:

import java.util.Random;

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

        random.ints(5, 1, 101)
              .forEach(System.out::println);
    }
}

The arguments represent:

5 = number of values
1 = inclusive minimum
101 = exclusive maximum

The code therefore prints five values between 1 and 100.

How to Generate Repeatable Random Numbers

Sometimes developers want the same sequence every time a program runs. This is useful for unit tests, simulations, and debugging.

Supply a fixed seed:

import java.util.Random;

public class Main {
    public static void main(String[] args) {
        Random random = new Random(12345L);

        System.out.println(random.nextInt(100));
        System.out.println(random.nextInt(100));
        System.out.println(random.nextInt(100));
    }
}

Running the same code with the same Java implementation and seed produces a repeatable sequence.

Repeatable output can help you reproduce a test failure. However, a predictable seed must not be used for security tokens, passwords, or verification codes.

How to Select a Random Item From an Array

Random number generation is often used to select an array element.

import java.util.Random;

public class Main {
    public static void main(String[] args) {
        String[] colors = {
            "Red",
            "Blue",
            "Green",
            "Yellow",
            "Purple"
        };

        Random random = new Random();

        int index = random.nextInt(colors.length);

        System.out.println(colors[index]);
    }
}

An array containing five elements has valid indexes from 0 through 4.

Passing colors.length to nextInt() automatically generates a valid index:

random.nextInt(colors.length)

The same technique works with arrays of names, questions, products, messages, game items, or other objects.

How to Generate Unique Random Numbers

Calling nextInt() multiple times does not guarantee unique results. The same number may appear more than once.

For a small predefined range, create a list, shuffle it, and select the required number of elements:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = IntStream
                .rangeClosed(1, 20)
                .boxed()
                .collect(Collectors.toCollection(ArrayList::new));

        Collections.shuffle(numbers);

        List<Integer> selected = numbers.subList(0, 5);

        System.out.println(selected);
    }
}

This example selects five unique values from 1 through 20.

For very large ranges, storing every possible value may consume unnecessary memory. In that situation, repeatedly generate values and store accepted results in a Set until the required number of unique values has been collected.

Common Mistakes When Generating Random Numbers

Forgetting That the Upper Bound Is Exclusive

This code does not generate 10:

random.nextInt(10);

It generates values from 0 through 9.

To include 10, use:

random.nextInt(11);

To generate 1 through 10, use:

random.nextInt(10) + 1;

Using Random for Security-Sensitive Values

The Random class is intended for general pseudorandom number generation. Do not use it for passwords, private tokens, encryption keys, reset links, or authentication codes.

Use SecureRandom for security-sensitive operations.

Using an Incorrect Range Formula

For an inclusive minimum and maximum, use:

random.nextInt(max - min + 1) + min;

Leaving out the +1 prevents the maximum value from being generated.

Creating a New Generator for Every Number

Avoid code like this inside a large loop:

for (int i = 0; i < 1000; i++) {
    Random random = new Random();
    System.out.println(random.nextInt(100));
}

Create one generator and reuse it:

Random random = new Random();

for (int i = 0; i < 1000; i++) {
    System.out.println(random.nextInt(100));
}

Assuming Random Values Are Always Unique

Randomness does not mean uniqueness. Two generated values can be identical.

Use a Set, shuffled list, or another uniqueness strategy when duplicate values are not allowed.

Which Java Random Number Method Should You Use?

Use Random for ordinary single-threaded applications, learning projects, games, simulations, and test-data generation.

Use Math.random() for short calculations when you only need a quick decimal result and do not need a reusable generator.

Use ThreadLocalRandom for concurrent or multithreaded applications where several threads frequently generate values.

Use SecureRandom for authentication codes, secure tokens, passwords, cryptographic operations, and other sensitive data.

Use RandomGenerator when working with Java 17 or newer and you want access to the modern random-number API or selectable generator algorithms.

The best method is determined by the application’s performance, compatibility, reproducibility, and security requirements.

Frequently Asked Questions

How do I generate a random number from 1 to 100 in Java?

Use the following expression:

int number = new Random().nextInt(100) + 1;

It returns an integer between 1 and 100, including both limits.

Can Java generate negative random numbers?

Yes. Calling nextInt() without a bound can return any valid int, including negative values:

int number = new Random().nextInt();

Is Math.random truly random?

No. It produces pseudorandom values generated by an algorithm. Its results are suitable for ordinary applications but not for security-sensitive operations.

What is the difference between Random and SecureRandom?

Random is designed for general pseudorandom values. SecureRandom provides cryptographically strong output intended for security-sensitive applications.

How do I generate a random Boolean in Java?

Use nextBoolean():

boolean result = new Random().nextBoolean();

The result will be either true or false.

How do I generate a random array index?

Pass the array length as the bound:

int index = random.nextInt(array.length);

Because the upper bound is excluded, the result will always be a valid index for a nonempty array.

Can a random number appear more than once?

Yes. Standard random generators allow duplicate results. Use a Set or shuffled collection when every selected number must be unique.

Conclusion

Understanding how to get random number in Java helps you build games, simulations, testing tools, selection systems, verification workflows, and many other applications.

For most beginner projects, the Random class is a practical starting point:

Random random = new Random();
int number = random.nextInt(100) + 1;

Use ThreadLocalRandom in concurrent applications, SecureRandom for sensitive values, and RandomGenerator when you want the modern Java random-generation API.

Always pay attention to whether a bound is inclusive or exclusive. Choosing the correct range formula and generator type will help you avoid off-by-one errors, security problems, duplicate-value assumptions, and unnecessary performance issues.