java generate random id

java generate random id

To generate a random ID in Java, you can use the SecureRandom class of the java.security package. The SecureRandom class generates random numbers that are suitable for use as cryptographic keys, and it is more secure than the Random class, which is provided in the java.util package.

Here's an example of how to generate a random ID using the SecureRandom class:

import java.security.SecureRandom;

public class Main {
  public static void main(String[] args) {
    SecureRandom random = new SecureRandom();

    // Generate a random ID as a hexadecimal string
    String id = String.format("%040x", new BigInteger(40, random));

    System.out.println(id); // prints a random hexadecimal string of length 40
  }
}
Source‮www:‬.lautturi.com

This code creates a SecureRandom object and uses it to generate a random BigInteger value. The BigInteger value is then formatted as a hexadecimal string using the String.format() method. The resulting string is a random ID of length 40.

You can use a similar approach to generate a random ID of any length, by specifying the desired length in the format string. For example, to generate a random ID of length 8, you can use the format string "%08x".

You can find more information about the SecureRandom class and the String.format() method in the Java documentation.

Created Time:2017-11-03 22:21:07  Author:lautturi