How do I generate a random int value in a specific range?

I have tried the following, but those do not work:

Attempt 1:

```randomNum = minimum + (int)(Math.random() * maximum);
// Bug: `randomNum` can be bigger than `maximum`.
```

Attempt 2:

```Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum =  minimum + i;
// Bug: `randomNum` can be smaller than `minimum`.```
Dec 22, 2020 in Java 544 views

## 1 answer to this question.

Before Java 1.7, the standard way to do this is as follows:

```import java.util.Random;

/**
* Returns a pseudo-random number between min and max, inclusive.
* The difference between min and max can be at most
* <code>Integer.MAX_VALUE - 1</code>.
*
* @param min Minimum value
* @param max Maximum value.  Must be greater than min.
* @return Integer between min and max, inclusive.
* @see java.util.Random#nextInt(int)
*/
public static int randInt(int min, int max) {

// NOTE: This will (intentionally) not run as written so that folks
// copy-pasting have to think about how to initialize their
// Random instance.  Initialization of the Random instance is outside
// the main scope of the question, but some decent options are to have
// a field that is initialized once and then re-used as needed or to
// use ThreadLocalRandom (if using at least Java 1.7).
//
// In particular, do NOT do 'Random rand = new Random()' here or you
// will get not very good / not very random results.
Random rand;

// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;

return randomNum;
}```
• 65,910 points

## How do I make a list with checkboxes in Java Swing?

Hii @kartik, Create a custom ListCellRenderer and asign it to ...READ MORE

## How do I convert a String to an int in Java?

Use the lines of code mentioned below:- String ...READ MORE

## How do I check if a string contains a substring in Java?

Hi@akhtar, The first and foremost way to check ...READ MORE

## How can I convert a String variable to a primitive int in Java

Here are two ways illustrating this: Integer x ...READ MORE

## How to compare Strings in Java?

String fooString1 = new String("foo"); String fooString2 = ...READ MORE

+1 vote

## How to generate random integers within specific range in Java?

You can achieve that concisely in Java: Random ...READ MORE

## How to divide a string in two parts

String s="yourstring"; boolean flag = true; for(int i=0;i<s.length();i++) { ...READ MORE

## How do I determine whether an array contains a particular value in Java?

Arrays.asList(yourArray).contains(yourValue) Warning: this doesn't work for arrays of ...READ MORE

## How do I check if a file exists in Java?

To test to see if a file ...READ MORE