Pages

Monday 22 December 2014

How to generate a random String in Java

The following function can be used to create a random string.
 private String getRandomString(int len){
    final String AB = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";  
    Random rand = new Random();  
    StringBuilder sb = new StringBuilder(len);
    for(int i=0; i<len; i++)
         sb.append( AB.charAt( rand.nextInt(AB.length()) ) );  
    return sb.toString();  
 }

You can call this java utility method to generate a random String of the choice of your own length.

Syntax:
getRandomString(int length); 

Note:Here length is the parameter which accepts the integer type and generates and returns a length character String.

For example:
     This is how you use this utility method.

 String randomStr = getRandomString(4);
 String ranString = getRandomString(8); 

Sample output(s):

gY5C
79V6yy2x