Java Math - random() Method
The Java 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).
public class MyClass { public static void main(String[] args) { System.out.println(Math.random()); System.out.println(Math.random()); System.out.println(Math.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).
public class MyClass { public static void main(String[] args) { System.out.println(Math.random()*10); System.out.println(Math.random()*10); System.out.println(Math.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).
public class MyClass { public static void main(String[] args) { System.out.println(Math.random()*2-1); System.out.println(Math.random()*2-1); System.out.println(Math.random()*2-1); } }
The output of the above code will be:
0.616550701127146 0.5330712637034409 -0.9722965205765486
❮ Java Math Methods