Random string generation

Is there any method in java to generate a random string of specified length.?
[84 byte] By [Dinesa] at [2007-11-26 20:02:32]
# 1
If not there will be as soon as you write it.
floundera at 2007-7-9 23:01:50 > top of Java-index,Java Essentials,New To Java...
# 2

I've never heard of one. It would be great if you created one :D

Perhaps make a random number between a certain ascii character and another ascii character, then convert that to the appropriate char value. Then from there, add the charValue.toString() onto an actual string.

I'd do this for however many different characters you need.

lethalwirea at 2007-7-9 23:01:50 > top of Java-index,Java Essentials,New To Java...
# 3

Here s the one i am using:

public static String generateKey(int length)

{

String sKey="";

int randInt;

Random random=new Random(System.currentTimeMillis());

long r1 = random.nextLong();

long r2 = random.nextLong();

String hash1 = Long.toHexString(r1);

String hash2 = Long.toHexString(r2);

sKey = hash1 + hash2;

if(sKey.length()>length)

{

sKey=sKey.substring(0,length);

}

return sKey.toUpperCase();

}

Dinesa at 2007-7-9 23:01:50 > top of Java-index,Java Essentials,New To Java...
# 4
I'll random from ascii 48 to 90, if what you want is alphanumeric =)
Icycoola at 2007-7-9 23:01:50 > top of Java-index,Java Essentials,New To Java...
# 5
why do u require it?
roaha at 2007-7-9 23:01:50 > top of Java-index,Java Essentials,New To Java...
# 6

> Here s the one i am using:

The method seems optimized. You get 16 random bytes (2 calls to Random). I suggest you instead create a char array of the wanted length. Then you fill it with length number of random chars of the kind you want. At the end you create a String from the char array. It will be length number of calls to Random but what the heck, it's not that expensive.

Fill a static array with the chars you desire and then generate a random index within the array. That will give you a random char. Then repeat X times where X is the number of chars you want in the String.

roaha at 2007-7-9 23:01:50 > top of Java-index,Java Essentials,New To Java...
# 7
If what you want are random hex digits, your method does not quite work. Long.toHexString does not provide leading zeros. Your results over the long term will have slightly fewer zeros than a true random string would have.
BillKriegera at 2007-7-9 23:01:50 > top of Java-index,Java Essentials,New To Java...