Search code examples
javarandompassword-generator

Generate a random string of specified length that contains only specified characters (in Java)


Does anybody know of a good way to generate a random String of specified length and characters in Java.

For example 'length' could be 5 and 'possibleChars' could be 'a,b,c,1,2,3,!'.

So

c!a1b is valid

BUT

cba16 is not.

I could try to write something from scratch but I feel like this must be a common use case for things like generating passwords, generating coupon codes, etc...

Any ideas?


Solution

  • You want something like this?

    Random r=new Random();
    
    char[] possibleChars="abc123!".toCharArray();
    int length=5;
    
    char[] newPassword=new char[length];
    
    for (int i=0; i<length;i++)
        newPassword[i]=possibleChars[r.nextInt(possibleChars.length)];
    
    System.out.println(new String(newPassword));