TheDeveloperBlog.com


Java

Java Random Numbers: Math.random

Random. Is randomness possible? Random numbers are usually pseudo-random. They give the appearance of randomness, but patterns still exist. Usually this is sufficient.


In Java we use the Random class, from java.util.Random to create a Random class. We call its methods to generate numbers. And with Math.random we have a shortcut.


Math.random. Consider this program. It calls the Math.random method and assigns a double variable to the result. That double is anywhere between 0 and 1.

Tip: For simple random needs, Math.random is sufficient. But using Random directly is better for more complex features.

Based on:

Java 7

Java program that uses Math.random

import java.lang.Math;

public class Program {
    public static void main(String[] args) {

	// Random number between 0 and 1.
	double value = Math.random();
	System.out.println(value);
    }
}

Output

0.24645081324805196

Random Object. Here we instantiate directly the Random class. With a Random instance, we call methods (like nextInt) to get the "next" random number.

Next: The Random object internally stores a state, based (by default) on a time seed. The stream returns the "next" number.

Argument: When we pass an argument to nextInt, the max integer returned is less than that value (not equal to it). It is greater than 0.

Java program that creates Random object

import java.util.Random;

public class Program {
    public static void main(String[] args) {

	// Create new Random and call nextInt on it twice.
	Random random = new Random();
	int random1 = random.nextInt();
	int random2 = random.nextInt(10);

	// Display results.
	System.out.println(random1);
	System.out.println(random2);
    }
}

Output

-1838898462
6

Random lowercase letters. This program uses Random to generate lowercase letters. These chars could be used to create random strings (or for other nefarious purposes).

First: We call nextInt with an exclusive bound of 26. This yields the values 0 through (and including) 25.

Add: We add 97 to the values to adjust to the lowercase characters (97 is the ASCII code for lowercase A).

Caution: This code does not handle international (Unicode) characters. It just handles lowercase ASCII letters. It is limited.

Java program that generates random lowercase letters

import java.util.Random;

public class Program {
    public static void main(String[] args) {

	Random random = new Random();

	// Generate 10 random lowercase letters.
	for (int i = 0; i < 10; i++) {
	    // Max value is exclusive.
	    // ... So this returns 1, 2, through 25.
	    int n = random.nextInt(26);

	    // Add 97 to move from integer to the range A to Z.
	    char value = (char) (n + 97);

	    // Display our results.
	    System.out.println(value + "..." + Integer.toString(n));
	}
    }
}

Output

s...18
o...14
y...24
d...3
t...19
p...15
q...16
f...5
f...5
h...7

Random text. We can use Random to generate random phrases (like a spam email). We use nextInt to generate random indexes into an array or ArrayList.

Then: We append the words at those random indexes into a StringBuilder. We use the array's length as the exclusive upper bound.

StringBuilderArrays

Finally: We capitalize the resulting phrase and remove its trailing punctuation. More advanced techniques are possible.

Markov chains: These are an algorithm used in the field of artificial intelligence. Markov chains can generate good random text.

Markov processes can also be used to generate superficially real-looking text given a sample document.

Markov chain: Wikipedia
Java program that generates random phrases

import java.util.Random;
import java.lang.StringBuilder;

public class Program {
    public static void main(String[] args) {

	// Create String array of words.
	String[] words = { "hello,", "cat,", "food", "buy", "free", "click",
		"here" };

	Random random = new Random();
	StringBuilder builder = new StringBuilder();

	// Append five random words to the StringBuilder.
	for (int i = 0; i < 5; i++) {
	    // Get random index (use length as nextInt is exclusive).
	    int index = (int) random.nextInt(words.length);
	    builder.append(words[index]);
	    builder.append(" ");
	}

	// Remove final space and trailing punctuation.
	builder.setLength(builder.length() - 1);
	if (builder.charAt(builder.length() - 1) == ',') {
	    builder.setLength(builder.length() - 1);
	}
	builder.append("!");
	// Uppercase the StringBuilder.
	builder.setCharAt(0, Character.toUpperCase(builder.charAt(0)));

	// Print result.
	System.out.println(builder);
    }
}

Output

Cat, free hello, food cat!

Shuffle array. With the Fisher-Yates shuffling algorithm, we make just one pass through an array, and rearrange all elements. This is fast. But the code seems prone to errors.

Shuffle

In quantum mechanics, at the heart of our universe, randomness exists. The world is not deterministic, but rather uncertain. This has little impact on Java programs.


With the Random class, we get a stream of pseudo-random numbers. For scientific work, or money-related programs, a better random stream can employed. But often Random is enough.