How to Generate Random Numbers in Java with Examples

Learn how to generate random numbers in Java using Math.random(), Random class, and DoubleStream with examples. In Java, random numbers are commonly used in games, simulations, testing, and security-related applications.

Code Explanation (Step-by-Step) :

Math.random() Method

  • Create an ArrayList<Double> to store random numbers.
  • Execute a for loop from 0 to 3.
  • Use Math.random() to generate a random double value between 0.0 and 1.0.
  • Multiply the random value by the loop variable i.
  • Add the generated value to the ArrayList.
  • Print all generated random numbers.

DoubleStream doubles() Method

  • Create an object of the Random class .
  • Use the doubles() method to generate a stream of random double values.
  • Specify:
    • Stream size as 4
    • Minimum value as 0
    • Maximum value as 1
  • Iterate through the stream using forEach().
  • Print each random number.
				
					import java.util.ArrayList;
import java.util.Random;
import java.util.stream.DoubleStream;

public class GenerateRandomNumber {

    public static void main(String[] args) {

        // Using Math.random()
        ArrayList<Double> randomNum = new ArrayList<>();

        for (int i = 0; i < 4; i++) {
            double value = i * Math.random();
            randomNum.add(value);
        }

        System.out.println("Generate Random Number using ArrayList: " + randomNum);
        System.out.println();

        // Using DoubleStream doubles()
        Random random = new Random();

        System.out.println("Generate Random Number using DoubleStream:");

        DoubleStream doubleStream = random.doubles(4, 0, 1);

        doubleStream.forEach(System.out::println);
    }
}
				
			

Output :-
Generate Random Number using ArrayList: [0.0, 0.9906354366238956, 0.7485715399071284, 0.618319353948994]

Generate Random Number using DoubleStream:
0.9968514060329906
0.8460632293034756
0.43730908284083425
0.5183778936650153

Difference Between Math.random() and Random Class in Java

Math.random() :

  • Generates a random double
  • Returns a number between 0 (inclusive) and 1.0 (exclusive).
  • No need to create an object.
  • Called directly using Math.random().
  • Suitable for simple random number generation.
  • Supports only double-type random values.
  • Less flexible compared to the Random class.
				
					double number = Math.random();
System.out.println(number);
				
			

Random Class :

  • Belongs to the java.util package.
  • Requires creating a Random object.
  • Can generate different data types such as int,double,long,float,boolean
  • Allows generating random numbers within a specified range.
  • Supports Java 8 stream methods such as: ints(),longs(),doubles()
  • More flexible and powerful than Math.random().
  • Commonly used in real-world applications.
				
					Random random = new Random();
int number = random.nextInt(100);
System.out.println(number);