SoFunction
Updated on 2025-05-22

Several common ways and applicable scenarios for random number generation in Java

Generating random numbers in Java can be achieved through a variety of methods. The following are several common methods and their applicable scenarios:

1. Basic methods: Random class and ()

  • Use classBy instantiatingRandomObject calls methods to generate random numbers of different types:

    Random random = new Random();
    int randomInt = (); // Generate integers in any rangeint rangedInt = (10); // Integers from 0 to 9double randomDouble = (); // 0.0arrive1.0floating point number

    If you need to generate integers of the specified range (such as 1-100):

    int min = 1, max = 100;
    int num = (max - min + 1) + min; // [4,5](@ref)
  • use()This method returns double precision floating point numbers between 0.0 and 1.0, suitable for generating simple decimals:

    double randomDouble = ();
    // Generate floating point numbers from 1.0 to 10.0double rangedDouble = 1.0 + (10.0 - 1.0) * (); [4](@ref)

2. Encryption security method: SecureRandom class

When it comes to cryptography or high security requirements (such as generating keys, tokens), useSecureRandom

import ;
SecureRandom secureRandom = new SecureRandom();
int secureInt = (1000); // generate0-999Encrypted secure random number [2,3](@ref)

andRandomcompared to,SecureRandomBased on encryption algorithms, it is more unpredictable, but has a higher performance overhead.

3. Generate a random number of specified digits

If you need to generate a random number of fixed digits (such as 6-bit verification code):

// Generate 6 digits (100000 to 999999)int length = 6;
int number = ((int) (10, length)) + (int) (10, length - 1); [2](@ref)

4. Seed control and repeatability

By setting seeds (seed), which makes the random number generation results repeatable and is suitable for testing scenarios:

Random seededRandom = new Random(12345L); // Fixed seedsint repeatableNum = (100); // The results are the same for each run [6](@ref)

5. Third-party library extension (Apache Commons Lang)

useRandomUtilsSimplified code:

import .;
int num = (1000, 10000); // generate4digit verification code [2](@ref)

​Application scenario selection suggestions

Scene Recommended method
Game, simple simulation Randomor()
Verification code, random ID RandomCombined with range calculation orRandomUtils
Encryption key, session token SecureRandom
Unit Testing SeedsRandomExample

With flexible selection methods, a balance between performance and security can be achieved. For higher performance or special distribution (such as Gaussian distribution), please refer toRandomClassicnextGaussian()Ways

Detailed introduction to the method

In Java, use()Generating random letters can be achieved by the following methods, combining the ASCII code range of characters or custom character sets to flexibly generate letters. The following are the specific implementation plan and sample code:

1. Generate a single random letter

1. Generate lowercase letters (a-z)

principle: The ASCII code range of lowercase letters is 97 ('a') to 122 ('z'), by()Generate an integer offset between 0 and 26 and convert it into characters.

char randomLower = (char) ('a' + () * 26);  
// Sample output:'k'、'd'wait

2. Generate capital letters (A-Z)

principle: The ASCII code range of capital letters is 65 ('A') to 90 ('Z'), and the method is similar to lowercase letters

char randomUpper = (char) ('A' + () * 26);  
// Sample output:'X'、'B'wait

3. Customize the letter range

General Method: Generate random letters (including boundaries) between the two by specifying the start and end characters.

public static char getRandomChar(char start, char end) {
    return (char) (start + () * (end - start + 1));
}
// Example: Generate letters between a-zchar customChar = getRandomChar('a', 'z');

2. Generate random alphabetical strings

If you need to generate a letter string of a specified length, you can loop to call the above method and splice the result:

1. Pure lowercase alphabetical strings

public static String generateLowerString(int length) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < length; i++) {
        ((char) ('a' + () * 26));
    }
    return ();
}
// Example:generateLowerString(5) → "bqthm"

2. Mixed upper and lower case letter strings

public static String generateMixedCaseString(int length) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < length; i++) {
        // Randomly select upper and lower case letters        boolean isLower = () < 0.5;
        char base = isLower ? 'a' : 'A';
        ((char) (base + () * 26));
    }
    return ();
}
// Example:generateMixedCaseString(6) → "JxRkYf"

3. Extended application: combination of letters and numbers

To generate a random string containing letters and numbers, you can define the character set and randomly select characters:

public static String generateAlphaNumeric(int length) {
    String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < length; i++) {
        int index = (int) (() * ());
        ((index));
    }
    return ();
}
// Example:generateAlphaNumeric(8) → "3hF8kZ2p"

​Things to note

  • Range control
    ()return0.0 ≤ value < 1.0,therefore() * nThe scope of0 ≤ value < n. If you need to include the upper limit value (such as generating integers of 1-10), you need to adjust the formula to(int) (() * (max - min + 1)) + min

  • Performance and Safety
    ()Suitable for simple scenarios. If you need high security (such as password generation), it is recommended to use it instead.SecureRandomkind.

Quote instructions

  • The ASCII code range definition of lowercase letters refers to the Java core classMathExample of application of class.
  • The string splicing method borrows the general implementation of random index of character arrays.
  • Methods for custom character ranges are derived from()Extended application.

Summarize

This is the article about several common ways and applicable scenarios for random number generation in Java. For more related content on random number generation of Java, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!