Wednesday, April 25, 2012

How to generate a random alphanumeric word with special characters of variable length

Usually we need to create a random word of some 8+ character to use as a password or an encryption key.
I have recently created this one, though very simple but very effective.
I have tried to replicate the same sequence and run in a loop of 1000000 iteration but with length of 8 characters there were no repetition. Hope the readers would like it.

package in.codeZila.www.utility;

public class RandomWordGenerator {

 public static final String getRandomWord(int length) {
  String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*";
  String rw = "";
  for(int i = 0; i < length; i++) {
   int index = (int) Math.floor(Math.random() * 62);
   rw += chars.charAt(index);
  }

  return rw;
 }
 
 public static void main(String[] args) {
  for(int i=0;i<100;i++){
   String randomPwd=getRandomWord(8);
   System.out.println(randomPwd);
  }
 }
 
}


The Random words generated are :

Please feel free to ask any doubts or clarifications.