Generating a random string

7 AM April 5, 2005

Here's a quick way to generate a short, random string in Java:

  Random r = new Random();

  String token = Long.toString(Math.abs(r.nextLong()), 36);

The resultant string is a maximum of ceil(ln(263) / ln(36)) = 13 characters long and is suitable for use as a temporary id or cookie name.

An even quicker and dirtier method is to simply convert a random double to a string:

  String token = "token" + Math.random();

This is useful in test cases and one-offs, but I wouldn't put it into production code.

By alang | # | Comments (12)
(Posted to javablogs and Java)
© 2003-2006 Alan Green