wood burning stoves*
The moose likes Java in General and the fly likes Generating random alphanumeric strings. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Generating random alphanumeric strings." Watch "Generating random alphanumeric strings." New topic
Author

Generating random alphanumeric strings.

Mani Ram
Ranch Hand

Joined: Mar 11, 2002
Posts: 1140
What is the best way to generate an alphanumeric string in Java (something like A4FC54 or 23H3YR)?


Mani
Quaerendo Invenietis
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
If each char is completely random, selected from [0-9A-Z], then I'd use a Random.nextInt(36) for each char. You can convert this int n to a character:

Then just put six of these in a StringBuffer, and you've got a random ID.
If you need to make sure no ID is ever repeated, you could add a HashSet which stores all the IDs used so far, and check each new random ID to see if it's in the set. If it is, then try again until you get something that isn't in the set.


"I'm not back." - Bill Harding, Twister
Wayne L Johnson
Ranch Hand

Joined: Sep 03, 2003
Posts: 399
I won't claim that this is the best way, but it works ...

It gives equal weight to the digits and the characters. You tell the method how long the string needs to be and it'll give you a string of that length with a random mix of alphanumerics.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Yup, I have one like that in my utility belt. And an overloaded method that lets you pass in the string of valid characters, so you could do something like leave out I and O to avoid confusion with 1 and 0, or leave out all the vowels to avoid accidental dirty words. Ya know about enough monkeys, enough typewriters ...


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Mani Ram
Ranch Hand

Joined: Mar 11, 2002
Posts: 1140
Thanks everybody.
Jim, I was thinking in line of Wayne, mainly for future enhancements (say, tomorrow they say that special characters are allowed in the string).
Actually the problem is more broader than what I initially asked for.
The requirement is to create a random alphanumeric string. (It is a weird requirement considering these strings are to be used as user id's! )
The system should generate a random string for the user id. So, basically I have to create a random string and check-it against a database to see whether it exists or not (I cannot cache it in a HashSet, for the list might be pretty big - in millions). If it exists already, then I have to try it again and again and again till I succeed.
So, there are 2 questions now
1. The characters inside the string should be random.
2. The string as a whole should be random enough from the previously created strings.
#1 has been answered here, though I'm not sure which is the best way
Any suggestions on #2? Will using a seed have an advantage or disadvantage in this case?
[ November 05, 2003: Message edited by: Mani Ram ]
Mani Ram
Ranch Hand

Joined: Mar 11, 2002
Posts: 1140

I can then have 2 loops, one to randomly pickup characters and another to pickup numbers. So I will end up with something like ABCD1234.
Now how will I shuffle it?
Should I do something like

Or is there a more elegant solution?
[ November 05, 2003: Message edited by: Mani Ram ]
Mani Ram
Ranch Hand

Joined: Mar 11, 2002
Posts: 1140
No more suggestions? Okay, so let me stick to the idea of Wayne with my shuffle() method (till someone else comes with a better idea).
But I have got another question now. As explained above, the program should generate a random string and check whether that string already exists in the database. If it exists already, I need to generate another string and try again. How can I implement this?
One way I can think of it is to use recursion.

But, I don't prefer the idea of using recursion. There should be a better alternative defiantly. Could somebody comment?
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 10908
    
  12

i wouldn't use recursion... doesn't seem to fit the model as you are not reducing to a simpler case each time.
why not just use a loop:

or am i missing something (very possible!!! )


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Well, this is one case where a do/while loop actually makes sense:

Sadly, this may be regarded as "hard to read" by some people. :roll: Anyway though, I agree - no need for recursion here.
Jim, I was thinking in line of Wayne, mainly for future enhancements (say, tomorrow they say that special characters are allowed in the string).
I agree, Wayne's solution is easier to read and maintain. The only reason to perfer my solution would be if you wanted to select randomly from a really large Unicode range. E.g. using all the CJK symbols. Unlikely, but possible.
I can then have 2 loops, one to randomly pickup characters and another to pickup numbers.
This solution might make sense if you want to control how many numbers there are, and how many letters (and yet you don't care about their position). I'm not sure how likely that is, but if that's what you want, you can certainly do it.
If you want to shuffle the contents of a StringBuffer, you can convert to a List of Characters and use Collections.shuffle() - or you can just steal the algorithm from the shuffle() source and apply it to the StringBuffer directly:

This is similar to the code you showed earlier, but a little differnt. I find the above algorithm easier to analyze and verify that each position has a 1/n chance of getting any given char from the original string. I think that's probably also true for the algorithm you show, but it's harder for me to see.
[ November 10, 2003: Message edited by: Jim Yingst ]
Mani Ram
Ranch Hand

Joined: Mar 11, 2002
Posts: 1140
Mmmm...actually myMethod() does more than what I have mentioned above and that was the reason why thought about recursion. But now I have refactored the method and I'm doing as you two have suggested.
JY: if you want to control how many numbers there are, and how many letters
Yes. That is what I'm trying to do. I have overloaded the method as
generateRandomString() - to generate a string with default number of letters & numerics
generateRandomString(int, int) - to generate a string with user specified number lengths.
Does that makes sense?
Regarding shuffling with StringBuffer instead of char array: Yes, your algorithm is clear, but will there be any performance drawbacks? (I know that the difference will not be noticeable in this particular example, but just curious to know in general)
[ November 10, 2003: Message edited by: Mani Ram ]
 
jQuery in Action, 2nd edition
 
subject: Generating random alphanumeric strings.
 
Similar Threads
Sorting Query problem in MySQL
Java Object Reference Variable Question
w00t: Word of the Year 2007
Alphanumeric sorting
Regex