Java Random Int

Generating random numbers is typically important in some applications that we do. For example, if we are writing a program that needs to shuffle a deck of cards, we can achieve that by swapping cards from random positions. In fact, many games requires random number generation because that makes each play unique from the previous one. Because if there is no randomness, then every time we play will feel the same. So below we try to show examples on how to generate Java Random Int values.

Random Int using java.util.Random

The most common and most famous way of generating random numbers of any kind, is by using the Random class. This is included in default Java under the java.util package, and is ready to use without requiring any external library such as Apache Commons or Google Guice. That is always a great news because we don't bloat our code base by using that.
Random Int from 0 to MAX using java.util.Random class
By default, the Random class has a nextInt() function that returns a number from 0 to some max values. Here is the syntax:
public int nextInt(int bound)
So it expects a parameter bound, which signifies what is the limit of the number we wish to generate. The range of values will start from 0 and the maximum is bound - 1. Meaning if we invoke nextInt(10), the method will return a random number from 0 to 9, excluding the number 10. We can use this method directly to get a random integer from 0 to some maximum value. Here is an example where we passed the same parameter 10 times:
System.out.println(new Random().nextInt(10));
System.out.println(new Random().nextInt(10));
System.out.println(new Random().nextInt(10));
System.out.println(new Random().nextInt(10));
System.out.println(new Random().nextInt(10));
System.out.println(new Random().nextInt(10));
System.out.println(new Random().nextInt(10));
System.out.println(new Random().nextInt(10));
System.out.println(new Random().nextInt(10));
System.out.println(new Random().nextInt(10));

And this is what I got from my box:

2
8
1
4
3
1
6
3
8
0

So it is indeed any value from 0 to 9, with 10 never being returned. But if we want from 0 to 10, we can just pass the value 11. For example:

System.out.println(new Random().nextInt(11));

Then this can output a number from 0 to 10.
Random Int from MIN to MAX using java.util.Random class

If we want a random number between some minimum number MIN to a maximum number MAX, we can use below formula for the Random.nextInt() ,method. that is this code:

new Random().nextInt(max - min + 1) + min;

So for example, we want a random number from 5 to 10, so that is around 6 possible values: 5, 6, 7, 8, 9, and 10. So to have 6 variations, we want to call nextInt(6) that gives 0 to 5. The values 0 to 5 gives 6 variation of values. But how do we derive 6? Than is exactly max - min + 1, or 10 - 5 + 1 = 6. And then since this will give 0 to 5, we will adjust by adding 5 after getting that random number, giving us values from 0+ 5 = 5, to 5 + 5 = 10, or 0 to 10. We wrap the example in a function and call it 10 times to prove the point:
public static void main(String[] args) {
    System.out.println(randomMinMax(5,10));
    System.out.println(randomMinMax(5,10));
    System.out.println(randomMinMax(5,10));
    System.out.println(randomMinMax(5,10));
    System.out.println(randomMinMax(5,10));
    System.out.println(randomMinMax(5,10));
    System.out.println(randomMinMax(5,10));
    System.out.println(randomMinMax(5,10));
    System.out.println(randomMinMax(5,10));
    System.out.println(randomMinMax(5,10));
    }
public static int randomMinMax(int min, int max) {
    return new Random().nextInt(max - min + 1) + min;
}

And we get exactly what we want!

6
10
6
5
7
6
8
8
5
10

Random Int using java.util.concurrent.ThreadLocalRandom

If thread safety and performance is important, we suggest to use the ThreadLocalRandom class instead of the regular Random class. Below is a converted example of what we did above:
Random Int from 0 to MAX using java.util.concurrent.ThreadLocalRandom class
ThreadLocalRandom have invisible constructor. The constructor was hidden on purpose because it manages the instance for us, to ensure than the generator is isolated to the particular thread. Hence we use the method current() to get the random number generator isolated to the thread where the code was executed.
System.out.println(ThreadLocalRandom.current().nextInt(10));
System.out.println(ThreadLocalRandom.current().nextInt(10));
System.out.println(ThreadLocalRandom.current().nextInt(10));
System.out.println(ThreadLocalRandom.current().nextInt(10));
System.out.println(ThreadLocalRandom.current().nextInt(10));
Random Int from MIN to MAX using java.util.concurrent.ThreadLocalRandom class
And we can also use ThreadLocalRandom to generate numbers from specific range of MIN MAX boundaries inclusive. See below modification:
public static int randomMinMax(int min, int max) {
    return ThreadLocalRandom.current().nextInt(max - min + 1) + min;
}
Again, we wish to use ThreadLocalRandom if we want a random number generator isolated to the current thread. It is initialized with an internally generated seed. It is recommended to use ThreadLocalRandom rather than shared Random objects in concurrent programs will typically encounter much less overhead and contention. We wish to use ThreadLocalRandom when multiple tasks use random numbers in parallel in thread pools.

Random Int using java.securityt.SecureRandom

The two Random classes introduced above have shortcomings, they are not cryptographically strong. If we wish to use a cryptographically strong random number generator that typically generates non-deterministic output, then SecureRandom is the recommended class to use. This is important if security is important to us, where we don't want to use deterministic algorithm to generate random numbers. See below the modified code for SecureRandom.
Random Int from 0 to MAX using java.securityt.SecureRandomclass
SecureRandom is similar to Random where we can just instantiate and start using it. See below:
System.out.println(new SecureRandom().nextInt(10));
Random Int from MIN to MAX using java.securityt.SecureRandom class
And we can also modify our method to use SecureRandom class in generating numbers:
public static int randomMinMax(int min, int max) {
    return new SecureRandom().nextInt(max - min + 1) + min;
}

Random Int using Math.random

The Math.random() generates a double number between 0 and less than 1. It is a static method that returns a double value with a positive sign greater than or equal to 0 but less than 1. It is pseudorandomly and uniformly distributed in the said range. Documentation says this method is properly synchronized to allow correct use by more than one thread. However, if many threads need to generate pseudorandom numbers at a great rate, it may reduce contention for each thread to have its own pseudorandom-number generator. Below is the syntax:
public static double random() 
Random Int from 0 to MAX using Math.random
So how do we generate an Int between 0 and MAX? By simply multiplying by MAX! See below:
System.out.println((int)(Math.random()*10));
System.out.println((int)(Math.random()*10));
System.out.println((int)(Math.random()*10));
System.out.println((int)(Math.random()*10));
System.out.println((int)(Math.random()*10));
System.out.println((int)(Math.random()*10));
System.out.println((int)(Math.random()*10));
System.out.println((int)(Math.random()*10));
System.out.println((int)(Math.random()*10));
System.out.println((int)(Math.random()*10));

So by simply multiplying by 10 we get output between 0 and 9. Simple! And below is the output of one test run:

6
4
7
8
1
2
5
9
6
8

Random Int from MIN to MAX using Math.random
Generating between a specific MIN MAX range is more tricky. But here is a solution that is similar to how we do above in Random classes:
public static int randomMinMax(int min, int max) {
    return (int)(Math.random() * ((max - min) + 1)) + min;
}

Random Int using Java 8 Random.ints

And if are using Java 8 or above, we can utilize Random.ints to generate our desired random numbers. Here is the syntax of Random.ints.
public IntStream ints(int randomNumberOrigin, int randomNumberBound)
It returns a stream of Int with values from randomNumberOrigin upto randomNumberBound. The documentation says calling this is equivalent to calling the following method:
int nextInt(int origin, int bound) {
  int n = bound - origin;
  if (n > 0) {
    return nextInt(n) + origin;
  }
  else {  // range not representable as int
    int r;
    do {
      r = nextInt();
    } while (r < origin || r >= bound);
    return r;
  }
}}
Random Int from 0 to MAX using Java 8 Random.ints

We rewrite our example using Java 8 Random.ints to generate a number between 0 and some number MAX.

System.out.println(new Random().ints(0, 10).findFirst().getAsInt());
System.out.println(new Random().ints(0, 10).findFirst().getAsInt());
System.out.println(new Random().ints(0, 10).findFirst().getAsInt());
System.out.println(new Random().ints(0, 10).findFirst().getAsInt());
System.out.println(new Random().ints(0, 10).findFirst().getAsInt());
System.out.println(new Random().ints(0, 10).findFirst().getAsInt());
System.out.println(new Random().ints(0, 10).findFirst().getAsInt());
System.out.println(new Random().ints(0, 10).findFirst().getAsInt());
System.out.println(new Random().ints(0, 10).findFirst().getAsInt());
System.out.println(new Random().ints(0, 10).findFirst().getAsInt());
So it is straightforward in the sense that we pass the numbers 0 and 10.

Random Int from MIN to MAX using Java 8 Random.ints

And given the sample above, we will just tweak this to give numbers between MIN ans MAX. See below code:

public static int randomMinMax(int min, int max) {
    return new Random().ints(min, (max + 1)).findFirst().getAsInt();
}