4

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?

asked Aug 1, 2016 at 14:38
3
  • 3
    Why don't you use string-handling functions? Just generate a random character in your desired range, in a loop, and keep concatenating it onto the string you're building. Also, why do you want to minimize imports? Commented Aug 1, 2016 at 14:40
  • There are no prizes for minimizing imports. It doesn't affect the time it takes to run, or even really the time to compile. Commented Aug 1, 2016 at 14:43
  • @hexafraction, yes, you are right, your method is rational. DanielM. thanks, I will notice that. But question is likely applied puzzle. Commented Aug 1, 2016 at 14:55

2 Answers 2

7

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();
}
answered Aug 1, 2016 at 15:33
Sign up to request clarification or add additional context in comments.

Comments

3

RandomStringUtils from commons-lang. If you don't wish to import, check out its source.

nanofarad
41.6k4 gold badges97 silver badges133 bronze badges
answered Aug 1, 2016 at 14:45

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.