Library contents

Java Math.random

Generate a pseudorandom double in the interval from zero inclusive to one exclusive.

A simple example

Math.random

  1. Start with One random draw
  2. Do this Check its permitted range
  3. Result Inside the range
The value can change with each draw. Here the useful result is whether it is between zero and one.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        double draw = Math.random();
        System.out.println(draw >= 0.0 && draw < 1.0);
    }
}
Output
true

Syntax

Java syntax
Math.random()
JDK 21 method signatures (1)
public static double random()
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Check the range of a random draw

A teacher is testing the draw used to assign practice exercises. The actual draw changes on each run, so the test checks whether it stays inside the promised interval, including its lower and upper boundaries.

From the programSystem.out.println(draw >= 0.0 && draw < 1.0)
Resulttrue
Main.java

class Main {
    public static void main(String[] args) throws Exception {
        double draw = Math.random();
        System.out.println(draw >= 0.0 && draw < 1.0);
    }
}
Output
true

Each draw can differ. Testing that it lies in the interval gives a reproducible true result.

Advertisements

Assign a practice station without indexing past the list

A teacher has four practice stations and wants to assign one for a warm-up. Convert a draw into a zero-based station index and verify the range instead of expecting the same station on every run.

From the programString[] stations = {"maps", "labels", "scales", "timers"}
First output linetrue
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String[] stations = {"maps", "labels", "scales", "timers"};
        int index = (int) (Math.random() * stations.length);
        System.out.println(index >= 0 && index < stations.length);
        System.out.println(!stations[index].isEmpty());
    }
}
Output
true
true

Multiplication scales the draw to less than four. Conversion to int chooses one of the four valid indices.

Assign a rehearsal station

A practice exercise replays a recorded draw so the teacher can check the assignment. Use a draw from zero inclusive to one exclusive. Multiply by the number of available stations and take the integer part to select a zero-based station.

GivenRecorded draw 0.625 · 8 stations
Worked result5

What to watch for

Use a cryptographic random generator for secrets. Math.random is intended for ordinary simulations.

Documentation for Math.random