Practical Coding in Java

Learn to write and validate your own code

Darren Kessner, PhD

(revised May 2026)

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.3957639765185825
0.7690269289242989
0.19530751277246705
0.9694943916971763
0.3038835414748008

Random doubles in [0,10):
9.41531442240018
6.969935678063842
6.928249075745319
0.5965680566099296
8.358318690248407

Random doubles in [200,210):
201.88983804481396
208.19563537645692
208.67937252478646
203.4397824160965
206.11560680957732

Random integers in [0,100):
86
69
64
53
22

Next: