Practical Coding in Java

Learn to write and validate your own code

Darren Kessner, PhD

(revised January 9, 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.9099673028945472
0.8410388850934784
0.6686992422260982
0.9936021433233518
0.8389127825125365

Random doubles in [0,10):
2.2823971946351094
7.60285634709729
8.929597433632923
4.255256856309933
0.9786122585729251

Random doubles in [200,210):
201.10537213543245
202.54928703937938
203.07717116117553
203.0251256482864
209.41085528720805

Random integers in [0,100):
36
78
62
4
37

Next: