.random()

The Math.random() method returns a pseudorandom double that is greater than or equal to 0.0 and less than 1.0 — [0.0, 1.0).

Syntax

Math.random()

The .random() method takes no parameters.

Example

The following example demonstrates using .random() to choose a number between 1 and 10:

public class Test {
public static void main(String args[]) {
double r = Math.random();
long n = Math.round((r * 10.0) + .5);
System.out.println(n);
}
}

The output will be a long type between 1 and 10.

Contributors

Interested in helping build Docs? Read the Contribution Guide or share your thoughts in this feedback form.

Learn Java on Codecademy