Question

Generate a Random Number in a Specific Range in Java and Android

kotlinjavaandroidrandom

Question

I want to generate a random number within a specific range in Android or Java, for example between 65 and 80.

I tried this code:

Random r = new Random();
int i1 = r.nextInt(80) + 65;

However, this is not giving the correct result. It can return values greater than the maximum value of 80.

How can I correctly generate a random integer between a minimum and maximum value?

Short Answer

By the end of this page, you will understand how to generate random integers inside a specific range in Java for Android, why nextInt() works the way it does, how to build the correct formula using a minimum and maximum value, and which common mistakes cause numbers to go outside the expected range.

Concept

In Java, Random.nextInt(bound) does not generate a number from 1 to bound. It generates a number from:

0 to bound - 1

So this code:

r.nextInt(80)

returns a value from 0 to 79.

If you then add 65:

r.nextInt(80) + 65

the final result becomes:

65 to 144

That is why your code can return values greater than 80.

To generate a random number between min and max inclusive, use this formula:

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

For example, for 65 to 80:

Random random = new Random();
int value = random.nextInt(80 - 65 + 1) + 65;

This works because:

  • 80 - 65 + 1 gives the size of the range
  • nextInt(rangeSize) produces a value starting at 0
  • adding 65 shifts that value into the desired range

This matters in real programming because random values are used in:

  • games
  • OTP/demo code generation
  • test data creation
  • shuffling and sampling
  • UI effects and simulations

If the range formula is wrong, the app may produce invalid values, bugs, or crashes.

Mental Model

Think of nextInt(bound) as a machine that always starts counting from 0.

If you want numbers in a different range, you do two things:

  1. Tell it how many numbers you need
  2. Shift the result to where your range starts

For the range 65 to 80:

  • The machine should produce 16 possible numbers
  • Those numbers are initially 0 to 15
  • Then you shift them by adding 65
  • Final result becomes 65 to 80

So the process is:

0..15  -> add 65 -> 65..80

That is the key idea: generate from zero, then shift into place.

Take Quiz

Syntax and Examples

The standard Java syntax is:

Random random = new Random();
int value = random.nextInt(max - min + 1) + min;

Example: random number from 65 to 80

import java.util.Random;

public class Main {
    public static void main(String[] args) {
        Random random = new Random();
        int value = random.nextInt(80 - 65 + 1) + 65;
        System.out.println(value);
    }
}

Possible output:

65
72
80
68

Example using variables

import java.util.Random;

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

        int min = 65;
        int max = 80;
        int value = random.nextInt(max - min + 1) + min;

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

This version is easier to read and reuse.

Android example

Random random = new Random();
int min = 65;
int max = 80;
int randomNumber = random.nextInt(max - min + 1) + min;

You can use this inside an Activity, Fragment, ViewModel, or any Java-based Android class.

Step by Step Execution

Consider this code:

Random random = new Random();
int min = 65;
int max = 80;
int value = random.nextInt(max - min + 1) + min;

Let’s trace it step by step.

Step 1: Calculate the range size

max - min + 1

becomes:

80 - 65 + 1 = 16

So now the code is effectively:

int value = random.nextInt(16) + 65;

Step 2: nextInt(16) generates a value from 0 to 15

Possible results:

0, 1, 2, ..., 15

Step 3: Add 65

If nextInt(16) returns 0:

0 + 65 = 65

If it returns 7:

7 + 65 = 72

If it returns 15:

15 + 65 = 80

Final result

The possible final values are:

65 to 80

inclusive.

Why your original code fails

Your code was:

r.nextInt(80) + 65
  • nextInt(80) returns 0 to 79
  • then adding 65 gives 65 to 144

So the upper limit becomes too large.

Real World Use Cases

Random numbers in a specific range are common in real apps.

Games

  • rolling dice
  • generating enemy damage values
  • random spawn positions within limits
int damage = random.nextInt(10 - 5 + 1) + 5;

OTP or verification demo values

  • generating a 4-digit or 6-digit demo code
int code = random.nextInt(9999 - 1000 + 1) + 1000;

Quiz or flashcard apps

  • selecting a random question index
  • picking random rewards

Test data generation

  • random ages, scores, ratings, or IDs for development
int age = random.nextInt(60 - 18 + 1) + 18;

UI behavior

  • random animation delays
  • random colors from a predefined set
  • random loading messages

The important part is that the result stays inside valid limits.

Take Quiz

Real Codebase Usage

In real projects, developers often wrap random-range logic inside a helper method so they do not repeat the formula everywhere.

Helper method

import java.util.Random;

public class RandomUtils {
    private static final Random random = new Random();

    public static int randomInRange(int min, int max) {
        if (min > max) {
            throw new IllegalArgumentException("min cannot be greater than max");
        }
        return random.nextInt(max - min + 1) + min;
    }
}

Usage:

int value = RandomUtils.randomInRange(65, 80);

Guard clause for validation

A common pattern is to validate inputs early:

if (min > max) {
    throw new IllegalArgumentException("Invalid range");
}

This prevents hidden bugs.

Configuration-driven values

Sometimes min and max come from:

  • app settings
  • remote config
  • API responses
  • form input

In those cases, validation becomes even more important.

Reusable utility pattern

Instead of scattering this logic across activities or fragments, teams often keep small utility functions in:

  • RandomUtils
  • NumberUtils
  • feature-specific helper classes

This makes code easier to test and maintain.

Common Mistakes

1. Using the max value directly in nextInt()

Broken code:

Random random = new Random();
int value = random.nextInt(80) + 65;

Problem:

  • this produces 65 to 144
  • 80 is treated as the count, not the final maximum

Fix:

int value = random.nextInt(80 - 65 + 1) + 65;

2. Forgetting the + 1

Broken code:

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

Problem:

  • this excludes the maximum value
  • for 65 to 80, you get 65 to 79

Fix:

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

3. Not validating min and max

Broken code:

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

If min > max, the bound becomes invalid and causes an error.

Fix:

if (min > max) {
    throw new IllegalArgumentException("min cannot be greater than max");
}

4. Creating too many Random objects unnecessarily

Less ideal:

int a = new Random().nextInt(10);
int b = new Random().nextInt(10);

Better:

Random random = new Random();
int a = random.nextInt(10);
int b = random.nextInt(10);

5. Confusing inclusive and exclusive ranges

Remember:

  • nextInt(bound) includes 0
  • nextInt(bound) excludes bound

So nextInt(5) gives:

0, 1, 2, 3, 4

not 0 to 5.

Comparisons

ApproachExampleResult RangeIncludes Max?Notes
Incorrect direct boundrandom.nextInt(80) + 6565..144No intended max controlWrong for custom range
Correct inclusive rangerandom.nextInt(max - min + 1) + minmin..maxYesMost common solution
Exclusive upper bound stylerandom.nextInt(max - min) + minmin..max-1NoUseful when upper bound should be excluded

Random vs Math.random()

OptionExampleNotes
Randomrandom.nextInt(max - min + 1) + minClear and common in Java/Android
Math.random()(int)(Math.random() * (max - min + 1)) + minWorks, but often less readable for integers

Random vs Kotlin random

If you are writing Kotlin instead of Java, you would usually write:

val value = (65..80).random()

That is simpler in Kotlin, but in Java and many Android codebases, Random is the common approach.

Take Quiz

Cheat Sheet

Generate random integer in an inclusive range

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

Example

Random random = new Random();
int value = random.nextInt(80 - 65 + 1) + 65;

What nextInt(bound) means

random.nextInt(5)

returns:

0, 1, 2, 3, 4

Rules

  • nextInt(bound) starts at 0
  • upper limit is excluded
  • use max - min + 1 for inclusive ranges
  • add min to shift into the correct range

Common formulas

Inclusive range min..max:

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

Exclusive upper bound min..max-1:

random.nextInt(max - min) + min

Validation

if (min > max) {
    throw new IllegalArgumentException("min cannot be greater than max");
}

Common bug

random.nextInt(max) + min

This is usually wrong for custom ranges.

FAQ

How do I generate a random number between 65 and 80 in Java?

Use:

Random random = new Random();
int value = random.nextInt(80 - 65 + 1) + 65;

Why does random.nextInt(80) + 65 go above 80?

Because nextInt(80) returns 0 to 79. After adding 65, the result becomes 65 to 144.

Does nextInt(bound) include the bound value?

No. It includes 0 and excludes bound.

How do I include both minimum and maximum values?

Use:

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

What happens if min is greater than max?

The formula becomes invalid and can throw an exception. Always validate the range first.

Can I use Math.random() instead of Random?

Yes:

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

But Random.nextInt() is often clearer for integer ranges.

Is this valid in Android?

Yes. Java's Random works in Android apps.

Take Quiz

Mini Project

Description

Build a small Java utility that simulates rolling a custom numbered token. The user provides a minimum and maximum value, and the program generates a random number inside that range. This demonstrates correct random-range logic and simple input validation.

Goal

Create a reusable method that returns a random integer between a given minimum and maximum value, inclusive.

Requirements

  1. Create a method that accepts min and max as parameters.
  2. Validate that min is not greater than max.
  3. Return a random integer within the inclusive range.
  4. Call the method multiple times to show different results.
  5. Use Java syntax compatible with Android projects.
Take Quiz

Keep learning

Related questions

View more