Using Math Random in Java

Math.random() returns a pseudorandom double greater than or equal to 0.0 and less than 1.0. To get a random integer in a range, multiply the result by the size of the range, cast it to int and add the lower bound. Math.random() is not cryptographically secure, so use SecureRandom for passwords and tokens. In this Java Math Random Example, we generate a random double and a random integer between 1 and 100. Click Execute to run the Java Math Random Example online and see the result.
Using Math Random in Java Execute
public class RandomNumberDemo {
    public static void main(String[] args) {
        double randomDouble = Math.random();
        System.out.println("Random double: " + randomDouble);

        int randomInt = (int) (Math.random() * 100) + 1;
        System.out.println("Random integer between 1 and 100: " + randomInt);
    }
}

Java Math.random() Syntax

random() is a static method of the Math class. It takes no arguments and returns a double.

Java Math.random() Syntax
public static double random()

The result is greater than or equal to 0.0 and less than 1.0. On the first call, Math.random() creates one java.util.Random generator and uses it for every later call.

Java Random Number Examples

The following are examples of generating random numbers in Java. Each example runs in the online Java code runner, and the numbers change on every run.

Get a random double between 0 and 1

Math.random() can return 0.0 but never returns 1.0.

Java Math.random() Example
public class RandomDoubleExample {
    public static void main(String[] args) {
        System.out.println(Math.random());
    }
}

// output: 0.6985144247405904

Get a random integer between 1 and 10

Multiply the result by 10, cast it to int to get a number from 0 to 9, then add 1.

Java Random Number Between 1 and 10 Example
public class RandomOneToTenExample {
    public static void main(String[] args) {
        int number = (int) (Math.random() * 10) + 1;
        System.out.println(number);
    }
}

// output: 4

Get a random integer in a range

For a range from min to max, both included, use min + (int) (Math.random() * (max - min + 1)).

Java Random Number in a Range Example
public class RandomRangeExample {
    static int randomInt(int min, int max) {
        return min + (int) (Math.random() * (max - min + 1));
    }

    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            System.out.println(randomInt(25, 50));
        }
    }
}

// output:
// 41
// 47
// 50

Get a random int with the Random class

The java.util.Random class has nextInt(bound), which returns an int from 0 to bound - 1.

Java Random nextInt() Example
import java.util.Random;

public class RandomClassExample {
    public static void main(String[] args) {
        Random random = new Random();
        int dice = random.nextInt(6) + 1;
        System.out.println("Dice: " + dice);
    }
}

// output: Dice: 4

See also

Updated: