Java.lang Package Classes

Java StrictMath - random() Method



The java.lang.StrictMath.random() method returns a double value in range [0.0, 1.0). The returned value is chosen pseudo-randomly from uniform distribution (approximately) from that range.

To generate a random in different range, the random() can be used. For example-

  • To generate a random number in range [0.0, 10.0), the expression random()*10 can be used.
  • To generate a random number in range [-1.0, 1.0), the expression random()*2 - 1 can be used.

Syntax

public static double random()

Parameters

No parameter is required.

Return Value

Returns pseudo-random double in range [0.0, 1.0).

Exception

NA.

Example:

In the example below, random() method is used to generate a pseudo-random double in range [0.0, 1.0).

import java.lang.*;

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

The output of the above code will be:

0.2778296598497003
0.6421976830440985
0.18591614847496474

Example:

In the example below, the method is used to generate a pseudo-random double in range [0.0, 10.0).

import java.lang.*;

public class MyClass {
 public static void main(String[] args) {
  System.out.println(StrictMath.random()*10);   
  System.out.println(StrictMath.random()*10);
  System.out.println(StrictMath.random()*10);     
 }
}

The output of the above code will be:

3.925911027583192
4.588044289363738
3.115186794654875

Example:

In the same way, it can be used to generate a pseudo-random double in range [-1.0, 1.0).

import java.lang.*;

public class MyClass {
 public static void main(String[] args) {
  System.out.println(StrictMath.random()*2-1);   
  System.out.println(StrictMath.random()*2-1);
  System.out.println(StrictMath.random()*2-1);     
 }
}

The output of the above code will be:

0.616550701127146
0.5330712637034409
-0.9722965205765486

❮ Java.lang - StrictMath