Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

Generating Random Numbers

Problem

You need to generate random numbers in a hurry.

Solution

Use java.lang.Math.random( ) to generate random numbers. There is no claim that the random values it returns are very good random numbers, however. This code exercises the random( ) method:

// Random1.java 
// java.lang.Math.random(  ) is static, don't need to construct Math 
System.out.println("A random from java.lang.Math is " + Math.random(  ));

Note that this method only generates double values. If you need integers, you need to scale and round:

/** Generate random ints by scaling from Math.random(  ).
 * Prints a series of 100 random integers from 1 to 10, inclusive.
 */
public class RandomInt {
    public static void main(String[] a) {
        for (int i=0; i<100; i++)
            System.out.println(1+(int)(Math.random(  ) * 10));
    }
}

See Also

Section 5.14 is an easier way to get random integers. Also see the Javadoc documentation for java.lang.Math, and the warning in this chapter’s Introduction about pseudo-randomness versus real randomness.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata