Sunday 26 May 2019

Java: Generate random alpha numeric string


Below snippet returns random string of fixed length.

public static String randomString(int len) {
         final StringBuilder builder = new StringBuilder(len);

         for (int i = 0; i < len; i++)
                  builder.append(ALPHA_NUMERICALS.charAt(rnd.nextInt(LENGTH)));
                 
         return builder.toString();
}

App.java
package com.sample.app;

import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;

public class App {

 private static final String ALPHA_NUMERICALS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
 private static SecureRandom rnd = new SecureRandom();
 private static final int LENGTH = ALPHA_NUMERICALS.length();

 public static String randomString(int len) {
  final StringBuilder builder = new StringBuilder(len);

  for (int i = 0; i < len; i++)
   builder.append(ALPHA_NUMERICALS.charAt(rnd.nextInt(LENGTH)));

  return builder.toString();
 }

 public static void main(String args[]) throws UnsupportedEncodingException {
  System.out.println(randomString(10));
 }

}

Sample Output
aKXQq3BNlG


You may like

No comments:

Post a Comment