Random numbers

How to generate a random number in Java

If you need to generate a random number in the Java programming language, then this article may help you. Please review the following sections to learn how to use the standard Java API to get a random integer, float or double value. Also, there are methods that allow you to generate arrays with random values.

Using the Math.random() method

The first method is very simple. The Math class provides the random() method. It can be used to generate a random double value in a range of 0.0 and 1.0 (exclusive). It means that the number 0.0 may be returned. However, the number 1.0 cannot be generated by that function. In addition, it is worth mentioning that the result is always a positive number.

Following is the specification of the Math.random() method:

public static double random()

Now, you can see a very simple application that uses this method to generate a random double value.

class sample {
    public static void main(String args[]) {
        double randomDouble = Math.random();

        System.out.println(randomDouble);
    }
}

If you run the given code, the console output should be like the following.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
0.3298577926538776

Generating a random integer using the Math.random() method

As you see, the Math.random() method returns the double number which is less than 1.0. However, such a number may not be suitable if you need to get some integer value.

There is a simple solution that allows you to convert a floating point number to a precise value. In the code below, we generate a number in a range of 0..99. Please also pay attention that there is a Math.floor() method. It is used to round the double value down.

class sample {
    public static void main(String args[]) {
        int randomDouble = (int) Math.floor(Math.random() * 100);

        System.out.println(randomDouble);
    }
}

Now, you may try to run our code. The application should output some random integer.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
31

Using the java.util.Random class

There is another more advanced method which allows you to generate a random number. Java language provides the Random class. It contains various helpful functions. Before using this class, you have to import it first. Then you can instantiate a required object that may be used to get random values.

Please see the below code. It shows how to correctly use this class in a very simple application.

import java.util.Random;

class sample {
    public static void main(String args[]) {
        Random randomGenerator = new Random();

        int randomNumber = randomGenerator.nextInt();

        System.out.println(randomNumber);
    }
}

The nextInt() method returns a random integer. Then, that value is printed to the standard console. If you run the given code, the output may be like the following.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
1235136002

Generating random number in a range of 0..99

If you need to generate a value in some range, then the nextInt() method may also help you. It accepts a single parameter which sets the bound of the returned value.

The following sample shows how to produce a value in a range of 0..99. Please pay attention that the parameter specifies a value which is not included in the result. That's why we use the number 100 there.

Now you can review the code:

import java.util.Random;

class sample {
    public static void main(String args[]) {
        Random randomGenerator = new Random();

        int randomNumber = randomGenerator.nextInt(100);

        System.out.println(randomNumber);
    }
}

If you try to run our sample, it should output a number which is less than 100.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
95

Generating random number in any range

In the previous section, we've described how to get integers which are equal or greater than zero. However, if you need to generate values in any range, then you may need to create a special method for that.

Below, you can see the NumberTools class. It provides the randomNumberInRange function, which accepts two parameters. If you call that method, you have to specify a range of the desired value. The number specified in the maxValue parameter is exclusive.

import java.util.Random;

class NumberTools {
    public static int randomNumberInRange(int minValue, int maxValue) {
        Random random = new Random();

        return random.nextInt(maxValue - minValue) + minValue;
    }
}

class sample {

    public static void main(String args[]) {
        int randomNumber = NumberTools.randomNumberInRange(100, 200);

        System.out.println(randomNumber);
    }
}

In the given code, we use a very simple algorithm that allows us to convert the given range to the range that is accepted by the nextInt() method.

Finally, if we try to run the given code, the output may be like the following.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
144

Configuring the random number generator

As you know, the Java core generates a pseudo number. There is an algorithm that makes values which are based on various factors. However, there is a risk that the same sequence of numbers can be reproduced in a different computer or environment. Usually, this is not a desired behavior in various applications that use authentication algorithms.

To solve this issue you may use the additional "seed" parameter. There, you have to supply a value that will randomize the number generator.

In our case, we get the current time and pass it into the constructor of the Random class. Please see the code sample below.

    import java.util.Random;

    class sample {
        public static void main(String args[]) {
            Random randomGenerator = new Random(System.currentTimeMillis());

            int randomNumber = randomGenerator.nextInt();

            System.out.println(randomNumber);
        }
    }

If you use that code in your application, there is a less chance that the same sequence of values can be reproduced in a different environment. But, there is no perfect solution and you may need to use different methods to improve the security of your application.

Generating a random double number

The Random class has special methods that can produce values of different types. For example, there is a method that allows you to generate a random double value. You can see how to use it in the following code sample.

import java.util.Random;

class sample {
    public static void main(String args[]) {
        Random randomGenerator = new Random();

        double randomNumber = randomGenerator.nextDouble();

        System.out.println(randomNumber);
    }
}

This simple application should output a random double value to the terminal, like it's shown below.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
0.6299662715663056

Generating a random float number

If you need to generate a float number instead of a double, then the Random class may help as well. There is a nextFloat() class that allows you to get the desired value. Please see the code sample below.

import java.util.Random;

class sample {
    public static void main(String args[]) {
        Random randomGenerator = new Random();

        float randomNumber = randomGenerator.nextFloat();

        System.out.println(randomNumber);
    }
}

However, there may be less numbers after the decimal point. That's because we get the float value. The output of the given code is below.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
0.43350476

Generating a random long number

You may also need to generate the long integer. There is a special function for that case as well. You may call the nextLong() method to get such a value. The following demo shows how to use this method.

import java.util.Random;

class sample {
    public static void main(String args[]) {
        Random randomGenerator = new Random();

        long randomNumber = randomGenerator.nextLong();

        System.out.println(randomNumber);
    }
}

The console output may be like the following:

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
2729111503768281295

Generating a random boolean value

The Random class also has a special function that allows you to get the random boolean value. The nextBoolean() method may return either true or false state. See the following code sample.

import java.util.Random;

class sample {
    public static void main(String args[]) {
        Random randomGenerator = new Random();

        boolean randomBoolean = randomGenerator.nextBoolean();

        System.out.println(randomBoolean);
    }
}

Now, you can try to run the given code. The console may have output like it's shown below.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
false

Generating array of random bytes

In the previous sections, we've described how to get a single value only. However, the Random() class also provides the nextBytes() method that can generate an array of random bytes. It can be helpful if you need to get many random values at once.

Before calling the specified method, you have to define the array that will hold the random values. After that you can call the nextBytes() method and it will fill the array with the random data.

Please see the following sample that demonstrates how this should be done.

import java.util.Arrays;
import java.util.Random;

class sample {
    public static void main(String args[]) {
        Random randomGenerator = new Random();

        byte[] randomBytes = new byte[10];

        randomGenerator.nextBytes(randomBytes);

        System.out.println(Arrays.toString(randomBytes));
    }
}

If you run the given code, it will print random bytes into the standard console.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
[92, 46, 52, -32, 125, -115, -63, -40, 90, 19]

Using the SecureRandom class

There may be a case when the regular random number generation methods are not applicable. As you know, there is a chance that some sequence of numbers may be predictable.

However, this is not acceptable in some conditions because of security concerns. For example, you are building an application that uses various encryption algorithms or there is an authentication mechanism in the code.

To solve that issue, Java provides the SecureRandom class. It uses different methods of randomizing the seed value. As a result, it may be harder to reproduce the same sequence of numbers on a different machine.

The sample of the code is provided below.

import java.security.SecureRandom;

public class sample {
    public static void main(String[] args) {
        SecureRandom random = new SecureRandom();

        int randomNumber = random.nextInt();

        System.out.println(randomNumber);
    }
}

If you run the given code, the output may be like the following.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
1474151941

As you see, we use the nextInt() method there. The methods are similar to those that are available in the Random() class. For example, you may also generate the random double value. See below how it can be done.

import java.security.SecureRandom;

public class sample {
    public static void main(String[] args) {
        SecureRandom random = new SecureRandom();

        double randomNumber = random.nextDouble();

        System.out.println(randomNumber);
    }
}

The console output should be like the following.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
0.9800294102889497

Using the SplittableRandom class

The SplittableRandom class was added in Java 8. It works differently than the previous methods. The main purpose of this class is that it can be used in parallel environments. There is a split() method that allows returning a new instance.

The API is similar to the Random class. Please review the following sample that shows how to use it.

import java.util.SplittableRandom;

public class sample {
    public static void main(String[] args) {
        SplittableRandom splittableRandom = new SplittableRandom();

        int randomNumber = splittableRandom.nextInt();

        System.out.println(randomNumber);
    }split()
}

Now, you can try to run the code and console output may be like the following.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
262685875

Using the ThreadLocalRandom class

Java also provides the ThreadLocalRandom class which should be used in a multi-threaded environment. It contains a random number generator that is attached to the current thread.

The usage of this class is shown below. The random value is generated in the main thread of the application. We use the current() method that returns an instance of the ThreadLocalRandom class. Then, the nextInt() method is called to get a random number.

import java.util.concurrent.ThreadLocalRandom;

public class sample {
    public static void main(String[] args) {
        System.out.println(ThreadLocalRandom.current().nextInt());
    }
}

If you run the given code sample, the console should have output like below.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
247544605

Also, the following is another demo that shows how to generate random numbers in separate threads. You can see the NumberGenerator class there. It contains the run() method that prints random integers to the console.

import java.util.concurrent.ThreadLocalRandom;

class NumberGenerator implements Runnable {
    @Override
    public void run() {
        System.out.println(ThreadLocalRandom.current().nextInt());
    }
}

public class sample {
    public static void main(String[] args) {
        Runnable generator = new NumberGenerator();

        for (int index = 0; index < 10; index++) {
            Thread task = new Thread(generator);
            task.start();
        }
    }
}

The above application will generate a list of multiple random numbers. The console output may be like the following.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
1027989419
-1684572256
1082383115
2081910423
-1424500768
-1094187884
2077867816
1952720836
-1763938332
1214957087

Conclusion

As you see, Java is a very feature rich programming language. There are many different methods that can be used to generate random numbers. You may choose a solution that is the most suitable in your specific case.

For simple applications, you may consider using the Math.random() method. Also, the java.util.Random class can be added to the code if you need to generate various types of data, like integers or double numbers.

However, if you need more security for your project, then you can try other methods. The SecureRandom class is a good candidate. It allows us to generate a less predictable sequence of numbers.

Related Articles

Gray and brown mountain

Converting byte array to string and vice versa in Java

Cup of coffee on saucer

How to read a file to string in Java

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *