Practical Coding in Java

Learn to write and validate your own code

Darren Kessner, PhD

(revised October 21, 2025)

Previous: HelloMath

HelloRandom

//
// HelloRandom.java
//


public class HelloRandom
{
    public static void main(String[] args)
    {
        // Math.random() returns a double in [0,1)

        System.out.println("Random doubles in [0,1):");
        for (int i=0; i<5; i++)
        {
            double value = Math.random();
            System.out.println(value);
        }

        // Multiplying by a value expands the range

        System.out.println();
        System.out.println("Random doubles in [0,10):");
        for (int i=0; i<5; i++)
        {
            double value = Math.random() * 10;
            System.out.println(value);
        }

        // Adding a value translates the range 

        System.out.println();
        System.out.println("Random doubles in [200,210):");
        for (int i=0; i<5; i++)
        {
            double value = Math.random() * 10 + 200;
            System.out.println(value);
        }

        // Casting to int gives the integer portion of the floating
        // point number (drops everything past the decimal point).

        System.out.println();
        System.out.println("Random integers in [0,100):");
        for (int i=0; i<5; i++)
        {
            int value = (int)(Math.random() * 100);
            System.out.println(value);
        }
    }
}

Output:

Random doubles in [0,1):
0.8297853411310505
0.5768037321938281
0.4287612373432833
0.2318114587548077
0.3971152064242588

Random doubles in [0,10):
1.7474277791391601
7.717911349721835
5.606794306846691
3.8179337134991775
7.851551804112953

Random doubles in [200,210):
209.74074564802493
201.45087151244357
204.37071757104624
209.51276356370263
204.25425698640635

Random integers in [0,100):
51
44
36
28
70

Next: