random() Method in Java

Rumman Ansari   Software Engineer   2019-03-30   6482 Share
☰ Table of Contents

Table of Content:


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.

The method is used to generate a random number between 0.0 and 1.0. The range is: 0.0 =< Math.random < 1.0. Different ranges can be achieved by using arithmetic operations.

Syntax

static double random()

Parameters

Here is the detail of parameters ?

  • This is a default method and accepts no parameter.

Return Value

  • This method returns a double.

Example

public class RandomMethod {

   public static void main(String args[]) {
      System.out.println( Math.random() );
      System.out.println( Math.random() );
   }
}

Output

0.7258237480180965
0.2591562227895975
Press any key to continue . . .

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.



/*
 * 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);


	}

}

Output

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.

Generated Random Number:0.4394187883009246
Press any key to continue . . .