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.14183496533422502
0.8804816171613596
0.3282317240689322
0.8899957938741168
0.12642313204813282

Random doubles in [0,10):
8.099738481091315
4.7987609248173335
8.11173254121222
1.735289052783393
8.588074602231409

Random doubles in [200,210):
206.03262535992297
207.5807533331273
205.62784606668743
205.72749183951666
209.5083522603224

Random integers in [0,100):
17
94
61
35
3

Next: