Java Math.random() Example

In Java, there is a method random() in the Math class, which returns a double value between 0.0 and 1.0. Note that the default random numbers are always generated in between 0 and 1. If you want to get the specific range of values, the you have to multiple the retruned value with the magnitue of the range. For example, if you want to get the random numbers between 0 to 20, the the returned value has to be multiplied by 20 to get the desired result. Lets look at the simple example to understand this concept:

MathRandomExample.java

package javabeat.net.util;
public class MathRandomExample {
	public static void main(String[] args) {
		double x = Math.random();
		double y = Math.random();
		System.out.println("Random Number 1 : " + x);
		System.out.println("Random Number 2 : " + x);
		//Get the random number between 1-30
		x = Math.random()*30;
		System.out.println("Random Number between 0 - 30 : " + x);
		//Convert to Integer
		int xInt = (int)(Math.random()*30);
		System.out.println("Random Number between 0 - 30 (Integer) : " + xInt);
		//Random numbet between 5-15
		xInt = 5 + (int)(Math.random()*10);
		System.out.println("Random Number between 5 - 15 (Integer) : " + xInt);

	}

}

Output…

Random Number 1 : 0.7050742837772005
Random Number 2 : 0.7050742837772005
Random Number between 0 - 30 : 9.97783862360115
Random Number between 0 - 30 (Integer) : 20
Random Number between 5 - 15 (Integer) : 13

If you look at the above code, Math.random() method generates the random number between 0-1. The next lines used that result and got the desired range of values like 0-30 and 5-15. I hope this example helps you to understand how to use the Math.random() utility method.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Pin It on Pinterest

Share This

Share this post with your friends!

Share This

Share this post with your friends!