.random()
Published Aug 24, 2022
Contribute to Docs
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.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Java
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.Beginner Friendly17 hours