Search⌘ K
AI Features

Generating and Using Random Numbers

Explore how to generate random numbers using Java's Random class and apply these values to arrays and strings. Understand how to select random elements, extract random characters, and shuffle arrays to build dynamic, unpredictable behaviors in your Java programs.

Randomness transforms static programs into dynamic applications. Whether we are selecting a random lottery winner, generating unpredictable enemy movements in a game, or creating randomized test data, we need a way to introduce unpredictability into our code. When we pair random number generation with the arrays and strings we just learned, we unlock the ability to build flexible, real-world behaviors that react differently every time our program runs.

The java.util.Random class

To generate random numbers in Java, we use the Random class from the java.util package. We create a Random object using the new keyword, which then gives us access to methods that produce randomized values. The most commonly used method is nextInt(int bound), which generates a random integer from 0 up to, but not including, the specified boundary. We can also generate random decimal values using nextDouble().

Java 25
import java.util.Random;
public class RandomDemo {
public static void main(String[] args) {
Random random = new Random();
int anyNumber = random.nextInt();
int zeroToNine = random.nextInt(10);
double decimal = random.nextDouble();
System.out.println("Random integer: " + anyNumber);
System.out.println("Random 0 to 9: " + zeroToNine);
System.out.println("Random decimal: " + decimal);
}
}
  • Line 1: We import the Random class so the compiler knows where to find it.

  • Line 5: We instantiate a new Random object to access its generation methods.

  • Line 7: We call nextInt() without arguments, which returns any possible valid Java integer, positive or negative.

  • Line 8: We pass 10 as the boundary. This generates a random integer from 0 through 9.

  • Line 9: We call nextDouble() to generate a decimal value between 0.0 (inclusive) and 1.0 (exclusive).

Selecting random array elements

Arrays and randomness are a perfect match. Because array indices always start at 0 and go up to length - 1, the nextInt(bound) method is exactly what we need. By passing the array’s length property as the boundary, we guarantee that the generated number will always be a valid, safe index for that specific array.

Java 25
import java.util.Random;
public class RandomArrayElement {
public static void main(String[] args) {
String[] rewards = {"Gold Coin", "Health Potion", "Magic Sword", "Empty Chest"};
Random random = new Random();
int randomIndex = random.nextInt(rewards.length);
String selectedReward = rewards[randomIndex];
System.out.println("You found a: " + selectedReward);
}
}
  • Line 5: We define an array of strings representing possible game rewards.

  • Line 8: We pass rewards.length (which is 4) into nextInt(). This returns a random integer from 0 to 3.

  • Line 10: We use the generated random integer to access an element from the array safely.

Extracting random characters from strings

We apply the exact same random-index logic to String objects. By using the string’s length() method to set our random boundary, we can generate a valid index and pass it to the charAt() method to extract a random character. This is the foundational technique for building features like randomized passwords or one-time passwords (OTPs) for two-factor authentication.

Java 25
import java.util.Random;
public class RandomPassword {
public static void main(String[] args) {
String validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
StringBuilder password = new StringBuilder();
Random random = new Random();
for (int i = 0; i < 6; i++) {
int randomIndex = random.nextInt(validChars.length());
char randomChar = validChars.charAt(randomIndex);
password.append(randomChar);
}
System.out.println("Generated code: " + password.toString());
}
}
  • Line 5: We define a pool of valid characters to draw from.

  • Line 6: We create a StringBuilder to efficiently construct our password character by character.

  • Line 9: We start a loop that will run six times to create a six-character string.

  • Line 10: We generate a valid index using validChars.length() as the exclusive upper bound.

  • Lines 11–12: We extract the character at that random index and append it to our StringBuilder.

Shuffling array data

Sometimes we need to rearrange an entire dataset rather than just picking a single item. We can shuffle an array by iterating through it and swapping each element with another element at a randomly chosen index. This requires a temporary variable to hold one value while we perform the swap, ensuring no data is overwritten or lost during the exchange.

Java 25
import java.util.Random;
import java.util.Arrays;
public class ArrayShuffle {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
Random random = new Random();
for (int i = 0; i < numbers.length; i++) {
int randomIndex = random.nextInt(numbers.length);
// Swap the current element with the random element
int temp = numbers[i];
numbers[i] = numbers[randomIndex];
numbers[randomIndex] = temp;
}
System.out.println("Shuffled array: " + Arrays.toString(numbers));
}
}
  • Line 9: We iterate through every element in the array from start to finish.

  • Line 10: We generate a random index that points to anywhere in the array.

  • Line 13: We store the value of the current element (numbers[i]) in a temporary variable so we do not lose it.

  • Line 14: We overwrite the current element with the value found at the random index.

  • Line 15: We place the original value (stored in temp) into the random index’s position, completing the swap.

Coupling the Random class with array boundaries and string lengths provides us with the tools to build unpredictable, dynamic behaviors. By safely restricting our random numbers to valid index ranges, we can extract, manipulate, and shuffle data with confidence, setting the stage for more complex algorithmic logic in our Java applications.