47

Possible Duplicate:
How to generate a random String in Java

I am wanting to generate a random string of 20 characters without using apache classes. I don't really care about whether is alphanumeric or not. Also, I am going to convert it to an array of bytes later FYI.

Thanks,

Community
  • 1
  • 1
novicePrgrmr
  • 18,647
  • 31
  • 81
  • 103

4 Answers4

92

Here you go. Just specify the chars you want to allow on the first line.

char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
StringBuilder sb = new StringBuilder(20);
Random random = new Random();
for (int i = 0; i < 20; i++) {
    char c = chars[random.nextInt(chars.length)];
    sb.append(c);
}
String output = sb.toString();
System.out.println(output);

If you are using this to generate something sensitive like a password reset URL or session ID cookie or temporary password reset, be sure to use java.security.SecureRandom instead. Values produced by java.util.Random and java.util.concurrent.ThreadLocalRandom are mathematically predictable.

Jonathan Leitschuh
  • 822
  • 1
  • 8
  • 29
WhiteFang34
  • 70,765
  • 18
  • 106
  • 111
  • 1
    this is not a good method...i tried getting hundred random nos. but very few were unique. I put this code in a while loop and iterated 0 to 99. many outputs were repeated.. – Nikhil Jun 20 '12 at 16:15
  • @Nikhil I suspect you did something wrong. If you need a better source of random numbers, try `SecureRandom` instead. That shouldn't matter for duplicates in this case though, looping over the above code I got these 100 unique strings: http://pastebin.com/ELZ950tk – WhiteFang34 Jun 21 '12 at 05:26
  • @WhiteFang34 Hi, I tried this code in a MIDlet. I assume this might be working fine on a desktop java application. You can check my results here :http://pastebin.com/yDcT41g8 . So when you use it in a MIDlet you get repeated strings. The only change i made was to use StringBuffer instead StringBuilder. – Nikhil Jun 21 '12 at 12:53
  • @WhiteFang34 Ok..just checked it in an usual java class...yes i get 100 unique strings...so this probably does not work well in midlet because the random class is prolly no so powerful...or something of that sort... – Nikhil Jun 21 '12 at 13:07
  • @Nikhil Ah, that's interesting. Perhaps the `Random` construction is getting the same seed (seems likely that it's using the system time and it's rounded). Try reusing the `Random` object by putting it outside of your loop. You should get the desired result since it'll keep generating different numbers from the same initial seed (use `SecureRandom` to prevent it from eventually repeating). – WhiteFang34 Jun 22 '12 at 00:54
  • 2
    @WhiteFang34 Yes..smooth. I put the random object out side of the loop and now the result is perfect. 100 randoms nos. is what i get. :) and white fang is a great book ;) ..i recommend call of the wild..just in case you haven't read it.. – Nikhil Jun 22 '12 at 03:22
  • another answer is here: http://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string – bmichalik Mar 16 '14 at 18:07
12

I'd use this approach:

String randomString(final int length) {
    Random r = new Random(); // perhaps make it a class variable so you don't make a new one every time
    StringBuilder sb = new StringBuilder();
    for(int i = 0; i < length; i++) {
        char c = (char)(r.nextInt((int)(Character.MAX_VALUE)));
        sb.append(c);
    }
    return sb.toString();
}

If you want a byte[] you can do this:

byte[] randomByteString(final int length) {
    Random r = new Random();
    byte[] result = new byte[length];
    for(int i = 0; i < length; i++) {
        result[i] = r.nextByte();
    }
    return result;
}

Or you could do this

byte[] randomByteString(final int length) {
    Random r = new Random();
    StringBuilder sb = new StringBuilder();
    for(int i = 0; i < length; i++) {
        char c = (char)(r.nextInt((int)(Character.MAX_VALUE)));
        sb.append(c);
    }
    return sb.toString().getBytes();
}
evandrix
  • 6,041
  • 4
  • 27
  • 38
corsiKa
  • 81,495
  • 25
  • 153
  • 204
5

You may use the class java.util.Random with method

char c = (char)(rnd.nextInt(128-32))+32 

20x to get Bytes, which you interpret as ASCII. If you're fine with ASCII.

32 is the offset, from where the characters are printable in general.

user unknown
  • 35,537
  • 11
  • 75
  • 121
3
public String randomString(String chars, int length) {
  Random rand = new Random();
  StringBuilder buf = new StringBuilder();
  for (int i=0; i<length; i++) {
    buf.append(chars.charAt(rand.nextInt(chars.length())));
  }
  return buf.toString();
}
maerics
  • 151,642
  • 46
  • 269
  • 291