How to assign a random number using a cryptographically secure random number generator in Java

1 Answer

0 votes
import java.security.SecureRandom;

public class SecureRandomExample {
    public static void main(String[] args) {
        // Create an instance of SecureRandom
        SecureRandom secureRandom = new SecureRandom();

        // Generate a random integer
        int randomInt = secureRandom.nextInt(); // Can be positive or negative
        System.out.println("Random Integer: " + randomInt);

        // Generate a random integer within a specific range (0 to 999999)
        int randomInRange = secureRandom.nextInt(1_000_000); // Upper bound is exclusive
        System.out.println("Random Integer in Range (0-999999): " + randomInRange);

        // Generate a random double between 0.0 (inclusive) and 1.0 (exclusive)
        double randomDouble = secureRandom.nextDouble();
        System.out.println("Random Double: " + randomDouble);
    }
}



/*
run:

run1:
Random Integer: 1994313195
Random Integer in Range (0-999999): 441520
Random Double: 0.053722696578379914

run2:
Random Integer: -838528242
Random Integer in Range (0-999999): 740623
Random Double: 0.2863056533105819

*/

 



answered Aug 20, 2025 by avibootz
...