Generating random numbers using Apache Commons Lang 3

suggest change

org.apache.commons.lang3.RandomUtils (Apache Commons Lang 3) can generate a random number in one call.

int x = RandomUtils.nextInt(1, 1000);

nextInt(int startInclusive, int endExclusive) takes a range. 1000 is not a possible result of the call above.

The same class generates long, double, float, boolean, and byte[] values. These are the RandomUtils methods as documented for Commons Lang 3.8:

static boolean nextBoolean() // Returns a random boolean.
static byte[] nextBytes(int count) // Creates an array of random bytes.
static double nextDouble() // Documented as a random double within 0 - Double.MAX_VALUE.
static double nextDouble(double startInclusive, double endInclusive) // Documented as a random double within the specified range.
static float nextFloat() // Documented as a random float within 0 - Float.MAX_VALUE.
static float nextFloat(float startInclusive, float endInclusive) // Documented as a random float within the specified range.
static int nextInt() // Documented as a random int within 0 - Integer.MAX_VALUE.
static int nextInt(int startInclusive, int endExclusive) // Returns a random int in that half-open range.
static long nextLong() // Documented as a random long within 0 - Long.MAX_VALUE.
static long nextLong(long startInclusive, long endExclusive) // Returns a random long in that half-open range.

The int and long ranges are start-inclusive and end-exclusive, so nextInt() never returns Integer.MAX_VALUE. The double and float parameters are named endInclusive in that release, but the implementation is start + (end - start) * nextDouble() (or nextFloat()). Random.nextDouble() and nextFloat() return a value in [0, 1), so the named upper bound is not returned. Start values must be non-negative, and a reversed range throws IllegalArgumentException.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents