In Java, Math.random generates a random number between 0.0 and 1.0. Such methods are present in almost all programming languages, rand() in C, random() in Python.

Likewise, for Java, we have Math.random() to do the job.

double myRandomNumber = Math.random();

Ever wondered how it worked? In this article, you will learn more about math.random() java function or method.

Computers can generate truly random numbers by observing some external data, like mouse movements or fan noise, which are not predictable and create data from it. This is known as entropy.

Other times, they generate “pseudorandom” numbers by using an algorithm so the results appear random, even though they aren’t.

The Math.random() the function returns such a pseudo-random number with approximately uniform distribution over the range 0 to 1 (including 0 and excluding 1) — which we can then scale to our desired range.

With all that being said, it is a fact that we can use this method in lots of situations and scenarios. This method has a lot more practical uses than theories to discuss.

Basic Use of Math.random in Java

To demonstrate the basics I have used a for-loop to iterate 5 times and generate 5 random numbers for 0 to 1 excluding 1.

public class RandomDemo {
	public static void main(String[] args) {
		for(int i = 0; i < 5; i++) {
			System.out.println("Random number "+(i+1)+": "+Math.random());


Random number 1: 0.4083247223370633
Random number 2: 0.1969001864492308
Random number 3: 0.26956654243092026
Random number 4: 0.8746480298131365
Random number 5: 0.06343364819000619

You can see that our random numbers are a bit ugly.

To Big decimals might not be useful to us. So we can simply multiply the fraction by 10 and round up the value using Math.round().

Alternatively, we can also explicitly type-cast it to an int data type. In this way, we can obtain a random number from 0 – 10.

Math.round() Java fucntion
Syntax: Math.round(10*Math.random())

Type Cast to int 
Syntax: (int)(10*Math.random())

Modified Output

Random number 1: 7
Random number 2: 4
Random number 3: 6
Random number 4: 7
Random number 5: 0

Roll Dice | Using random function in Java to generate the outcomes

With the basics clear, we can try a simple program called ‘RollDice’.

dice math random java

Find the value of dice using math random function in java

Create a method called rollDice() which returns a random integer between 1 and 6 every time it is called.

[Hint: adjust the range with proper factor. Remember if we round numbers between 0 and 0.5, we get 0. It is not a valid move.]

Great! We hope you succeeded. Here’s the solution for you.

public class RandomDemo {
	static int rollDice() {
		return (int)(Math.random()*6 + 1);
	public static void main(String[] args) {	
		for(int i = 0; i < 5; i++) {
			System.out.println("Dice value "+(i+1)+": "+rollDice());


Dice value 1: 4
Dice value 2: 3
Dice value 3: 6
Dice value 4: 6
Dice value 5: 2

The real solution is this line: return (int)(Math.random()*6 + 1);. We generated a random number between 0 and 1 excluding 1 and multiplied it with 6.

Note if 1 is excluded then the product will always be greater or equal to 0 and less than 6. It may be 5.999..9 but no matter.

Typecasting to int will result in loss of the decimal data and we shall get 5 only. Therefore it is important to add 1 at the end to make sure we get ‘6’ too. Also adding 1 increases the lower bound from 0 to 1.

Still not sure that the values are random? Execute the code over and over again. Every time the result set will be different!

Value of pi using Math.random Java

An interesting problem that requires the use of random numbers.

Write a Program to calculate the value of pi.

We know that the value is 22/7 approximately 3.141592653589793238. But can we derive it using a program? This question is more about mathematics less about code.

Value of pi using Math.random Java


[Hint: Imagine a square of side 1 with one of its vertexes as the center of a circle of radius 1. Now generate random points (x,y) within the square and check whether it lies in or outside the circle. The ratio of points inside circle and points outside circle will be equal to pi/4]

Hope you tried. Here’s the solution for help.

public class CalcPi {
	static double calculatePi(int iteration) {
		int pointsInCircle = 0;
		for(int i=0 ; i<iteration; i++) {
			double x = Math.random();
			double y = Math.random();
			// if x and y satisfies x^2 + y^2 <= r^2
			// the point lies in the circle
			if((x*x) + (y*y) <= 1) {
		return (double)pointsInCircle/iteration*4;
	public static void main(String[] args) {




circle example


In the method calculatePi(int iteration) we have received an integer parameter ‘iteration‘.

The loop runs this many times. Each time it generates a random point P(x,y) and if the point lies in the circle of radius 1 it increments ‘pointsInCircle‘ by 1.

After the loop ends we return the value of (points in the quarter-circle divided by points in the square).

Note that all points generated are inside the square of side 1 since Math.random returns a number between 0 and 1 excluding 1. Therefore we use the number of iterations as the number of points inside the square.

With an increasing number of iterations, the value of pi will tend to be more accurate.

Moreover, every time the code has executed the result will fluctuate. The fluctuations will keep decreasing with the increasing number of iterations. So, if you try to generate the same list, you will probably get a similar but different data set.

Here is the comparative list.

1. System.out.println(calculatePi(10)); output: 2.8
2. System.out.println(calculatePi(100)); output: 2.92
3. System.out.println(calculatePi(1000)); output: 3.22
4. System.out.println(calculatePi(10000)); output: 3.15
5. System.out.println(calculatePi(100000)); output: 3.1438
6. System.out.println(calculatePi(1000000)); output: 3.141832

Read more awesome Java tutorials such as Binary Tree in Java.

We hope this tutorial helped you to achieve the same. Keep learning keep sharing. Follow us on Facebook and Instagram.