Java Random Number Generator — How to Generate Integers With Math Random

Thanoshan MV
3 min readJan 26, 2021

Computer-generated random numbers are divided into two categories: true random numbers and pseudo-random numbers.

True random numbers are generated based on external factors. For example, generating randomness using surrounding noises.

But generating such true random number is a time-consuming task. Therefore, we can utilize pseudo-random numbers which are generated using an algorithm and a seed value.

These pseudo-random numbers are sufficient for most purposes. For example, you can use them in cryptography, in building games such as dice or cards, and in generating OTP (one-time-password) numbers.

In this article, we will learn how to generate pseudo-random numbers using Math.random() in Java.

1. Use Math.random() to Generate Integers

Math.random() returns a double type pseudo-random number, greater than or equal to zero and less than one.

Let’s try it out with some code:

public static void main(String[] args) {
double randomNumber = Math.random();
// output #1 = 0.5600740702032417
// output #2 = 0.04906751303932033

randomNumber will give us a different random number for each execution.

Let’s say we want to generate random numbers within a specified range, for example, zero to four.

// generate random numbers between 0 to 4
public static void main(String[] args) {
// Math.random() generates random number from 0.0 to 0.999
// Hence, Math.random()*5 will be from 0.0 to 4.999
double doubleRandomNumber = Math.random() * 5;
System.out.println("doubleRandomNumber = " + doubleRandomNumber);
// cast the double to whole number
int randomNumber = (int)doubleRandomNumber;
System.out.println("randomNumber = " + randomNumber);
/* Output #1
doubleRandomNumber = 2.431392914284627
randomNumber = 2

When we cast a double to int, the int value keeps only whole number part.

For example, in the above code, doubleRandomNumber is 2.431392914284627 . doubleRandomNumber's whole number part is 2 and fractional part (numbers after the…

Thanoshan MV

My notes, findings, thoughts and investigations.