Tutorial by Examples

Java provides, as part of the utils package, a basic pseudo-random number generator, appropriately named Random. This object can be used to generate a pseudo-random value as any of the built-in numerical datatypes (int, float, etc). You can also use it to generate a random Boolean value, or a random...
The method nextInt(int bound) of Random accepts an upper exclusive boundary, i.e. a number that the returned random value must be less than. However, only the nextInt method accepts a bound; nextLong, nextDouble etc. do not. Random random = new Random(); random.nextInt(1000); // 0 - 999 int num...
Random and ThreadLocalRandom are good enough for everyday use, but they have a big problem: They are based on a linear congruential generator, an algorithm whose output can be predicted rather easily. Thus, these two classes are not suitable for cryptographic uses (such as key generation). One can ...
/** * returns a array of random numbers with no duplicates * @param range the range of possible numbers for ex. if 100 then it can be anywhere from 1-100 * @param length the length of the array of random numbers * @return array of random numbers with no duplicates. */ public static int[] ...
//Creates a Random instance with a seed of 12345. Random random = new Random(12345L); //Gets a ThreadLocalRandom instance ThreadLocalRandom tlr = ThreadLocalRandom.current(); //Set the instance's seed. tlr.setSeed(12345L); Using the same seed to generate random numbers will return the sa...
We can use org.apache.commons.lang3.RandomUtils to generate random numbers using a single line. int x = RandomUtils.nextInt(1, 1000); The method nextInt(int startInclusive, int endExclusive) takes a range. Apart from int, we can generate random long, double, float and bytes using this class. R...

Page 1 of 1