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.7299923064292348
0.7920777233897016
0.5189363167808713
0.6511918019895695
0.12534462205932162

Random doubles in [0,10):
0.7247511895464998
6.230044179489176
6.58889408370058
6.6865322621553425
4.5583678972159

Random doubles in [200,210):
205.8472802958255
203.34921622130466
201.14489239537883
204.75621938174345
200.74143598559343

Random integers in [0,100):
6
51
86
14
66

Next: