Random numbers are extremely useful and important. They are used in almost every game to set chances of things happening (think dice rolls, etc), as well as in cryptography.

As in many things in Java, there is more than one way to make random numbers.

Method 1: use Math.random

double d = Math.random(); //this does the standard thing and returns a double between 0 and 0.99999 int r = (int)(Math.random() * n) + 1; //this makes random integers from 1 to n

**How it works:**

- Math.random() returns a number between 0.00000 and 0.9999999
- If you multiply this number by 10, you get a number between 0.0000 an 9.9999999
- Similarly multiplying by any integer, eg. 15, gives you a range of numbers from 0.000 to 14.999999 (just slightly less than the integer you chose)
- Take the integer portion of this, getting rid of the decimals: we now have a number between 0 and 14 (inclusive)
- Add 1 to it to get a number from 1 to 15.
- If you added 16 to it, you would get a random number between 16 and 30 (inclusive)

Method 2: make a Random object

import java.util.Random; Random randGen = new Random(); //DO NOT make a new randGen for each number. int r1 = randGen.nextInt(); //any valid integer (i.e. from -2,147,483,648 to 2,147,483,647) int r2 = randGen.nextInt( n ); // any integer from 0 to n-1 int r2 = randGen.nextInt(100) +1; // an integer from 1 to 100 double r3 = randGen.nextDouble(); //this does the standard thing and returns a double between 0 and 0.99999. //once you've created your Random object (randGen) and your r2 variable, //each time you want a new random number, just type r2 = randGen.nextInt(100) +1

Method 3:

For super random numbers, use `java.security.SecureRandom`

. It's good to know this if you need to do anything involving securely transmitting information over the internet.

Neither method gives you random integers between n1 and n2.

Neither method gives you random integers spaced out, e.g. random multiples of 3 between 1 and 100.

For both of these situations you have to do the math yourself.

I use Math.random() because it's shorter: ` int rand = (int)(Math.random() * 10) + 1;`

Here's the identical code for util.Random, which a lot of people still use:

```
import java.util.Random;
Random randgen = new Random();
int rand = randGen.nextInt(10) + 1;
```