Random numbers can be generated using the java.util.Random
class or Math.random()
static method. There is no need to reinvent the random integer generation when there is a useful API within the standard Java JDK. Unless you really really care for performance then you can probably write your own amazingly super fast generator. In this tutorial I’ve chosen for the java.util.Random class because I find it more readable witch results in cleaner and more understandable code. Remember you write it once and you or someone else will read it many many many times.
The Minimum (min) value cannot be greater than the Maximum (max) value. For simplicity I did not make an assert in the methods themselves.
package com.sheting.basic.utilities;
import java.util.Random;
public class RandomRange {
private static Random rnd = new Random();
// Generates a random number between min (inclusive) and max (inclusive)
public static int nextIncInc(int min, int max) {
return rnd.nextInt(max - min + 1) + min;
}
// Generates a random number between min (inclusive) and max (exclusive)
public static int nextIncExc(int min, int max) {
return rnd.nextInt(max - min) + min;
}
// Generates a random number between min (exclusive) and max (inclusive)
public static int nextExcInc(int min, int max) {
return rnd.nextInt(max - min) + 1 + min;
}
// Generates a random number between min (exclusive) and max (exclusive)
public static int nextExcExc(int min, int max) {
return rnd.nextInt(max - min - 1) + 1 + min;
}
}
Instances of java.util.Random are threadsafe. However, the concurrent use of the same java.util.Random instance across threads may result in poor performance. Consider instead using ThreadLocalRandom in multithreaded designs.
Instances of java.util.Random are not cryptographically secure. Consider instead using SecureRandom to get a cryptographically secure pseudo-random number generator for use by security-sensitive applications.