Java - simple random util generator with min max in range API methods

10 points
Created by:

1. Overview

In java core there is couple of different ways to generate random numbers. Usually it is a bit confusing which one to use. Also there are libs to solve this problem eg RandomDataGenerator (Apache Commons Math API). This util aims to help java developers to have simple random util with short and intuitive API.

Below Util implements API:

  • int nextInt()
  • long nextLong()
  • float nextFloat()
  • double nextDouble()
  • int nextIntBetween(int min, int max)
  • long nextLongBetween(long min, long max)
  • float nextFloatBetween(float min, float max)
  • double nextDoubleBetween(double min, double max)

2. RandomUtil source code

import java.util.concurrent.ThreadLocalRandom;

public class RandomUtil {

	public static int nextInt() {
		return ThreadLocalRandom.current().nextInt();

	public static long nextLong() {
		return ThreadLocalRandom.current().nextLong();

	public static float nextFloat() {
		return ThreadLocalRandom.current().nextFloat();

	public static double nextDouble() {
		return ThreadLocalRandom.current().nextDouble();

	public static int nextIntBetween(int min, int max) {
		return ThreadLocalRandom.current().nextInt(min, max);

	public static long nextLongBetween(long min, long max) {
		return ThreadLocalRandom.current().nextLong(min, max);

	public static float nextFloatBetween(float min, float max) {
		return (ThreadLocalRandom.current().nextFloat() * (max - min)) + min;

	public static double nextDoubleBetween(double min, double max) {
		return ThreadLocalRandom.current().nextDouble(min, max);

Usage example

public static void main(String[] args) {
	System.out.println(RandomUtil.nextInt()); // 814082468
	System.out.println(RandomUtil.nextLong()); // 6168205606450145596
	System.out.println(RandomUtil.nextFloat()); // 0.9008545
	System.out.println(RandomUtil.nextDouble()); // 0.6147962628743574

	System.out.println(RandomUtil.nextIntBetween(2, 50)); // 31
	System.out.println(RandomUtil.nextLongBetween(2L, 500L)); // 348
	System.out.println(RandomUtil.nextFloatBetween(2.0f, 4.0f)); // 2.3247766
	System.out.println(RandomUtil.nextDoubleBetween(2.0d, 4.0d)); // 2.0241598371950804


  1. ThreadLocalRandom - Java docs
  2. Random - Java docs
  3. RandomDataGenerator (Apache Commons Math API)

Checkout latest findings & news:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Rockstar community members
Thank you for great work 👍