Stack Exchange
How can I generate a random 7-character alphanumeric string?
I did the stuff like this but not working. the base48Encode method parameter I have passed the current system time in milli secs
private static final String CHARACTER_SET = "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ";

public static String base48Encode(double d) {
    Double num = Double.valueOf(d);
    Integer length = CHARACTER_SET.length();
    String encodeString = new String();
    while (num > length) {
        encodeString = CHARACTER_SET.charAt(num.intValue() % length) + encodeString;
        num = Math.ceil(new Double(num / length) - 1);
    }
    encodeString = CHARACTER_SET.charAt(num.intValue()) + encodeString;

    return encodeString;
}


Possible duplicate? http://stackoverflow.com/questions/363681/generating-random-numbers-in-a-range-with-java

Are you asking for a random 7 digit number, or a random 7 character value? The title of your question and the content of it are conflicting.

sorry for the confusion, it should be mixture of alphanumeric, I won't get duplicate values in any scenario.

Have a look at RandomStringUtils from Apache Commons. You can probably use the randomAlphanumeric() method.

Your requirements as stated are contradictory. Random cannot be unique by definition.

I'd suggest renaming the method - "encode" implies a reversible process, which this is not.

@mustaccio correct, yet many unique id generators are based solemnly on random generators - UUID version 4 to name one.


I won't get duplicate values in any scenario.

It's not possible to 100% guarantee a unique value (especially given a string of 7 characters) due to the Birthday Paradox. Given a character set containing 48 characters, selecting 7 at random, you'd have a 1% chance of collision after only 110,000 random values.
You can help mitigate this by doing two things.

Use a larger character set.
Increase the length of your random value.

Using a character set of 64 characters and selecting 10 at random would greatly decrease your chance of a collision, down to a 1% after 160,000,000 random values.
Rather than using currentTimeMillis to generate a value, which would cause a collision if you generated two values within the same millisecond, I'd suggest just using the Random class (which is seeded from the current time down to the nanosecond).
private static final String CHARACTER_SET = "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ";
private static Random rnd = new Random();

public static String randomString(int length){
    StringBuilder builder = new StringBuilder();
    for(int i = 0; i < length; i++){
        builder.append(CHARACTER_SET.charAt(rnd.nextInt(CHARACTER_SET.length())));
    }
    return builder.toString();
}


thanks Syon! I agree, It's not possible to 100% guarantee a unique value (especially given a string of 7 characters)
