CodeGym /Java Blog /Java Math /Generating random numbers in Java
Author
Oleksandr Miadelets
Head of Developers Team at CodeGym

Generating random numbers in Java

Published in the Java Math group
Random numbers are frequently used in programming for various applications, such as simulations, games, and cryptography. It could be, for example, password generators on websites or world generators in games. In Java language, you can generate random numbers using different techniques and classes the Java API provides. This topic covers how to generate random numbers in Java.

What Is a Random Number?

A random number in programming is a value that appears to be chosen without any specific pattern or order. It's like picking a number from a hat without knowing what you'll get. These numbers are generated by algorithms and are often used to introduce unpredictability and variety into computer programs. Computer programs use algorithms to generate random numbers. Such algorithms are called pseudo-random number generators (PRNG) because they produce sequences of numbers that appear random but are actually determined by a starting value called a seed.

Pseudorandom number generation algorithm

A pseudorandom or so-called random number generation algorithm uses a mathematical function to generate a sequence of numbers that appear random. However, these numbers are not truly random, as they are based on an initial value called a seed. One simple pseudorandom number generation algorithm is a linear congruential generator (LCG). LCG uses the following formula to generate the next number in the sequence: x_n = (a * x_(n-1) + c) % m where:
  • x_n — the next number in the sequence
  • x_(n-1) — the previous number in the sequence
  • a is the multiplication coefficient
  • c is the shift coefficient
  • m is the modulus
Let’s do it in Java.

public class Random {

    private int seed;

    public Random(int seed) {
        this.seed = seed;
    }

    public int nextInt() {
        int a = 1103515245;
        int c = 12345;
        int m = (int) (Math.pow(2, 31) - 1);


        int x = (a * seed + c) % m;
        seed = x;

        return x;
    }
}
The method we've provided is an attempt to create a pseudo-random number generator. However, it’s somewhat simplified and has a few issues: Seed Value: A good PRNG should start with a random or unpredictable seed value. Using a fixed seed value defeats the purpose of randomness. Typically, the seed should be based on some unpredictable source, like the current time. Modulus Operation: The modulus operation (%) can introduce bias in the generated numbers. It may not distribute numbers uniformly. Constants: The constants we've used (a, c, and m) are specific to certain PRNG algorithms like the Linear Congruential Generator (LCG). LCGs can be simple but are known to have some limitations in terms of the randomness and period of generated numbers. Predictability: Even with corrections, this code would still not be suitable for cryptographic or security-related applications because it's not cryptographically secure. It's fine for basic simulations or games where true randomness isn't critical. Of course, this code can be changed, but as you can see, this is not a trivial task for beginners. For most practical purposes, it's better to use Java's built-in java.util.Random class, which is designed to generate random numbers with a more extensive and tested algorithm. In the Java language, you can generate random numbers using different libraries and classes. Let’s take a glimpse at some of them.

Using the java.util.Random Class

The java.util.Random class is a commonly used class for generating random numbers in Java. Here's a simple example of random numbers using Java Random Class:

import java.util.Random;

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

   // random number generation: integer between 1 and 100
   int randomNumber = random.nextInt(100) + 1;
   System.out.println("Random number between 1 and 100: ");
   System.out.println("This time the number = " + randomNumber);
}
}
In this example, we create an instance of the Random class and use the nextInt() method to generate a random number (integer) between 1 and 100. The output generated number, sure, will be different every time.
Random number between 1 and 100: This time the number = 36

Using Math.random() Method

Another way to generate random numbers in Java is by using the Math.random() method, which returns a random double value between 0.0 (inclusive) and 1.0 (exclusive). You can scale this value to your desired range, such as generating random integers. Here is an example of random numbers using Math.random():

public class MathRandomExample{
   public static void main(String[] args) {
       // Generate a random double between 0.0 (inclusive) and 1.0 (exclusive)
       double randomValue = Math.random();

       // Scale the value to a random integer between 1 and 100
       int randomNumber = (int) (randomValue * 100) + 1;
       System.out.println("Random number from 1 to 100: ");
       System.out.println("This time the random Number =  " + randomNumber);
   }
}
The output here could be like this:
Random number from 1 to 100: This time the random Number = 98

Using the java.security.SecureRandom Class (For Secure Applications)

It's a good idea to use the Java.security for cryptographic or highly secure applications.SecureRandom class. It provides a more secure way to generate random numbers.

import java.security.SecureRandom;

public class SecureRandomExample {
    public static void main(String[] args) {
        SecureRandom secureRandom = new SecureRandom();
        
        // Generate a random integer between 1 and 100
        int randomNumber = secureRandom.nextInt(100) + 1;
        System.out.println("Random number from 1 to 100: ");
        System.out.println("This time the random Number =  " + randomNumber);
    }
}
Now we have an output like this (or with other number from 1 to 100):
Random number from 1 to 100: This time the random Number = 92

Conclusions

Random numbers in programming are essential for adding unpredictability, variety, and security to computer applications. They are generated using algorithms, and while they may not be truly random, they introduce uncertainty into various aspects of programming, from games to encryption. Understanding random numbers is a fundamental concept for any programmer, and it opens the door to exciting and diverse applications.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION