Description

On this document we will be showing a java example on how to use the random() method of Math Class. The random() returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.

Most of the methods of the Math class is static and the negateExact() method is no exception. Thus don’t forget that in order to call this method, you don’t have to create a new object. Use the method in the format Math.random().

 

This method is really helpful especially in designing algorithm that requires probability.

Notes:

  • ArithmeticException will be throw if the operation overflows the specified data type.

Method Syntax

public static double random()

Method Returns

The random() method returns a pseudorandom double greater than or equal to 0.0 and less than 1.0.

Compatibility

Requires Java 1.0 and up

Java Math random() Basic Example

Below is a java code demonstrates the use of random() method of Math class. The example presented is the simplest form of the usage of random method.

package com.javatutorialhq.java.examples;


/*
 * This example source code demonstrates the use of  
 * Random() method of Math class
 * Generating random numbers from 0.0 to 1.0
 */

public class MathRandomExample {

	public static void main(String[] args) {
		
		// Generate random number
		double rand = Math.random();
		System.out.println("Generated Random Number:"+rand);	
		
		
	}

}

The above java example source code demonstrates the use of random() method of Math class. We simply generate a random number and then print the result.

Sample Output

Below is the sample output when you run the above example.

java lang Math random() basic example output

Java Math random() Advance Example

Below is a java example on the use of random() method in generating a random number from 1 to 10.

package com.javatutorialhq.java.examples;


/*
 * This example source code demonstrates the use of  
 * Random() method of Math class
 * Generating random numbers from 1 to 10
 */

public class MathRandomExample {

	public static void main(String[] args) {
		
		// define the range
		int max = 10;
		int min = 1;
		int range = max - min + 1;		
		
		// generate random number from 1 to 10
		int rand = (int) (Math.random()* range) + min;
		System.out.println(rand);
		
	}

}

The above java example source code demonstrates the use of random() method of Math class. This second example is a little more advance since on this example we would be generating a random number that is within range. We just apply some mathematical project and making use of casting to get the desired random number.

Sample Output

Below is the sample output when you run the above example.

java lang Math random() advance example output