GETTING A RANDOM NUMBER A frequently asked Java forum question is, "How do I get a random integer?" For something that is so simple in other languages, it's remarkable how much effort it requires in Java, both in finding the classes and using them. The Java Random API spreads across packages and has grown with each Java version. As each new version is released, the best way of dealing with a random number changes. The first and simplest way of obtaining a random value is through the static random() method of java.lang.Math. This method returns a double, so it's typical to do: int n = ... int rnd = (int)(Math.random()*n); Another class existed for handling random numbers, but it failed to consider the ability to pass in an 'n.' This class, java.util.Random, used the OS clock to seed the random algorithm. Otherwise, a seed could be passed. If the same seed is used twice, the random numbers are guaranteed to be the same. For example: Random rnd = new Random(42L); int i = rnd.nextInt(); Random rnd2 = new Random(42L); int j = rnd.nextInt(); // i == j is true Java 1.1 added a nextBytes(byte[]) method to the Random class and an extension to Random named SecureRandom. The nextBytes method allows an empty byte array to be passed, then filled with random byte-values. The java.security.SecureRandom class allowed a cryptographic-quality pluggable algorithm to be used to create the random values. By default, the JDK comes with an algorithm named "SHA1PRNG." SecureRandom secrnd = SecureRandom("SHA1PRNG"); byte[] bytes = new byte[128]; secrnd.nextBytes(bytes); In 1.2, java.util.Random introduced a nextInt(n) method. The implementation is more complex than the simple code, and this allows for numbers that are more random. This method allows a random number to be gained without need for much thought. Though not having an easy accessor in java.lang.Math means there will still be posts to forums, the answer can now be simple; see java.util.Random.nextInt(int). Using this is easy: int n = 13; Random rnd = new Random(); // random number between 0 and 12 int r = rnd.nextInt(n); // random number between -5 and 7 int x = rnd.nextInt(n) - 5; REFERENCES: * java.util.Random javadoc http://click.online.com/Click?q=52-LUXoIrJGIRbzUtcMW7S2tqQfQoZR * java.lang.Math javadoc http://click.online.com/Click?q=c3-x1yCQJLeNf0PEEMZ57eU-udMxcRR * java.security.SecureRandom javadoc http://click.online.com/Click?q=a6-9zw4QCUWLIW6RtQOvxoQngjNsCFR -------------------------------------------