C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: For simple random needs, Math.random is sufficient. But using Random directly is better for more complex features.
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
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
Tip: With a static Random field, we reduce object creation, and avoid any time-based seed issues from code that executes near in time.
Note: Random uses a seed based on the time. So if we call it many times near in time, it may lead to poor results. A field helps.
Java program that uses static Random field
import java.util.Random;
public class Program {
static Random _random = new Random();
static void test() {
// Use static Random instance.
// ... This reduces object creation.
int number = _random.nextInt(5);
System.out.println(number);
}
public static void main(String[] args) {
// Call test method three times.
test();
test();
test();
}
}
Output
3
0
2
Here: We use a single array of size 10. We then fill it with random bytes 5 times and print them to the terminal.
Java program that gets random byte array
import java.util.Random;
public class Program {
public static void main(String[] args) {
Random random = new Random();
byte[] array = new byte[10];
// ... Generate random bytes 5 times.
for (int i = 0; i < 5; i++) {
// Fill existing array with random bytes.
random.nextBytes(array);
// Display.
for (int x = 0; x < array.length; x++) {
System.out.print(array[x]);
System.out.print(" ");
}
System.out.println();
}
}
}
Output
-95 49 92 -106 117 67 -97 116 109 100
-8 -50 -18 63 82 -10 122 6 -51 74
-25 -36 54 37 -115 -8 -61 21 43 63
-44 105 107 -109 -100 -4 41 -19 127 -91
-116 12 49 100 -110 -58 -83 -84 44 26
Stream: An IntStream is a specialized stream. For stream-based designs, the Random.ints() method can help simplify code.
StreamJava program that uses Random.ints
import java.util.PrimitiveIterator;
import java.util.Random;
import java.util.stream.IntStream;
public class Program {
public static void main(String[] args) {
// Use ints to get a random stream of ints.
Random r = new Random();
IntStream stream = r.ints();
PrimitiveIterator.OfInt iterator = stream.iterator();
// Call nextInt on the iterator to get random numbers.
for (int i = 0; i < 5; i++) {
int n = iterator.nextInt();
System.out.println(n);
}
}
}
Output
-1775913741
1599836970
515709788
1578549166
7961094
Then: We append the words at those random indexes into a StringBuilder. We use the array's length as the exclusive upper bound.
StringBuilderArrayFinally: We capitalize the resulting phrase and remove its trailing punctuation. More advanced techniques are possible.
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!
Quote: Markov processes can also be used to generate superficially real-looking text given a sample document.
Markov chain: Wikipedia