Java .random()

StevenSwiniarski's avatar
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).

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours

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.

All contributors

Contribute to Docs

Learn Java on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours