Practical Coding in Java

Learn to write and validate your own code

Darren Kessner, PhD

(revised September 1, 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);
        }

        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);
        }

        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);
        }

        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.7014722597039651
0.5201414396696359
0.09984441252727838
0.8753981452285116
0.54847854244902

Random doubles in [0,10):
1.1663874220649961
4.801221245712766
8.452328363574148
9.867377164322509
0.13839014778496028

Random doubles in [200,210):
203.33141093006617
203.72093391403254
206.75863225741566
209.26876107737968
204.76131404962968

Random integers in [0,100):
82
54
4
71
55

Next: