Generate Random Numbers in Java



In this article, we will learn to generate random number strings in Java. Random numbers are vital in programming for tasks like testing, cryptography, and simulations. A common need is generating random numeric strings, such as verification codes or randomized data. This article uses two Java methods Math.random() for simplicity and the Random class for flexibility and efficiency.

Problem Statement

Create a program to generate a random string consisting of numeric characters. The string's length should be customizable, and each character must be selected randomly. 

Input

num[] = { '0', '1', '2', '3', '4', '5' };

Output

33241

A random string of numeric characters based on the specified length and range

Using Math.random()

The Math.random() method generates random doubles between 0.0 and 1.0. By manipulating these values and using arrays for custom digit ranges, this approach is simple and ideal for small-scale randomization.

Creating a StringBuilder and using append() to create random numbers string out of it ?

int len = 5;
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < len; i++) {
 strBuilder.append(randomNum());
}

Returns the random number string using math.floor() method ?

public static char randomNum() {
 return num[(int) Math.floor(Math.random() * 5)];
}

Example

Below is an example of generating random number strings using Math.random() method ?

public class Demo {
   static char num[] = { '0', '1', '2', '3', '4', '5' };
   public static char randomNum() {
      return num[(int) Math.floor(Math.random() * 5)];
   }
   public static void main(String[] args) {
      int len = 5;
      StringBuilder strBuilder = new StringBuilder();
      for (int i = 0; i < len; i++) {
         strBuilder.append(randomNum());
      }
      System.out.println("Random numbers string = "+strBuilder.toString());
   }
}

Output

Random numbers string = 23024

Using Random Class

Java's Random class offers methods like nextInt() for efficient number generation within specified ranges. It's optimized for broader use cases and repeated tasks, making it a versatile choice for numeric string generation.

Following are the steps for generating random number strings using a random class ?

  • Create a Random Object: Instantiate a Random object to generate random numbers using its built-in methods.
  • Generate Random Numbers: Use random.nextInt() to generate random integers within a specific range (e.g., 0-9).
  • Build the String: Use a loop to append the generated random digits to a StringBuilder until the desired string length is achieved.
  • Output the Result: Convert the StringBuilder to a string and print it to the console as the final random number string.

Example

Below is an example of generating random number strings using a random class ?

import java.util.Random;

public class RandomNumberString {
   public static void main(String[] args) {
      int len = 5;  // Length of the random number string
      Random random = new Random();
      StringBuilder strBuilder = new StringBuilder();

      for (int i = 0; i < len; i++) {
         // Generate a random digit from 0 to 9
         int digit = random.nextInt(10);
         strBuilder.append(digit);
      }
      System.out.println("Random numbers string = " + strBuilder.toString());
   }
}

Output

Random numbers string = 23024

Comparison Table

Aspects Math.random() Random class
Range Handling Requires manual logic (e.g., Math.floor with arrays). Offers built-in methods like nextInt(range) for easy range control.
Performance Slower for repetitive tasks due to lack of optimization. More efficient for repeated or large-scale random operations.
Ease of Use Simplifies custom digit ranges using arrays. Easier for standard numeric ranges without arrays.
Reusability Less reusable due to inline randomness generation. Reusable through a single Random object across multiple calls.
Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-01-02T19:15:26+05:30

512 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements