Reputation: 135
What is the most simple way? Minimizing any imports.
This one is good:
String str = Long.toHexString(Double.doubleToLongBits(Math.random()));
But it's not perfect, for example it complicates with custom length.
Also an option: How to make this String unique?
Upvotes: 4
Views: 9128
Reputation: 106
Create a String of the characters which can be included in the string:
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Generate an integer using the Random class and use it to get a random character from the String.
Random random = new Random();
alphabet.charAt(random.nextInt(alphabet.length()));
Do this n times, where n is your custom length, and append the character to a String.
StringBuilder builder = new StringBuilder(n);
for (int i = 0; i < n; i++) {
builder.append(/* The generated character */);
}
Together, this could look like:
private static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
public String generateString(int length) {
Random random = new Random();
StringBuilder builder = new StringBuilder(length);
for (int i = 0; i < length; i++) {
builder.append(ALPHABET.charAt(random.nextInt(ALPHABET.length())));
}
return builder.toString();
}
Upvotes: 7
Reputation: 9086
RandomStringUtils from commons-lang. If you don't wish to import, check out its source.
Upvotes: 3