Sunday, January 26, 2014

How to generate a random String?

Source:
import java.util.Random;

public class RandomString {
   public static void main(String[] args) {

      String string = null;

      // Size of random string
      int length = 10;

      char[] text = new char[length];
      Random random = new Random();

      //All the characters available for random string
      String characters = "abcdefABCDEF12345";

      for (int i = 0; i < length; i++) {
         text[i] = characters.charAt(random.nextInt(characters.length()));
      }

      string = new String(text);
      System.out.println( string );

   }
}

Output:
   $ java RandomString 
   4BaADeBAce

Blog Archive