Generate random numbers using Random class

This code example generates random numbers using the java.util.Random class.
Here’s a step-by-step explanation of the code:

  1. The java.util.Random class is imported so that it can be used in the code.
  2. The main method of the RandomNumbersExample class is defined.
  3. An object rand of the Random class is created using the new keyword.
  4. A variable upperLimit is declared and initialized with the value 10. This variable will be used to specify the upper limit of the range of random numbers that will be generated.
  5. Three variables randomInteger, randomFloat, and randomDouble are declared. The rand.nextInt(upperLimit) method is called to generate a random integer, and the rand.nextFloat() and rand.nextDouble() methods are called to generate a random float and random double, respectively.
  6. The generated random numbers are printed to the console using the System.out.println() method.
  7. A for loop is used to generate and print 10 random numbers in the range 0 to 49. The rand.nextInt(50) method is called inside the loop to generate a random integer in the range 0 to 49. The generated random integer is then printed to the console.

The output of the code will be 10 random numbers of different data types (integer, float, and double) and 10 random numbers in the range 0 to 49.

import java.util.Random;

public class RandomNumbersExample {
    public static void main(String[] args) {
        Random rand = new Random();
        int upperLimit = 10;

        int randomInteger = rand.nextInt(upperLimit);
        float randomFloat = rand.nextFloat();
        double randomDouble = rand.nextDouble();

        System.out.println("random integer: " + randomInteger + "\nrandom float: " + randomFloat + "\nrandom double: "
                + randomDouble);
        System.out.println("random numbers:");

        for (int counter = 1; counter <= 10; counter++) {
            System.out.print(rand.nextInt(50) + " ");
        }
    }
}
Output first run
random integer: 3
random float: 0.2686128
random double: 0.20795575941751465
random numbers:
41 38 31 36 40 34 47 29 33 26
Output second run
random integer: 6
random float: 0.71186566
random double: 0.8480369669637289
random numbers:
5 47 37 40 17 22 13 37 8 13