Question:
How can I generate a random alpha numeric string?
Answer:
Using a random number generator to index valid letters for your string.
Code:
import java.util.Random; public class RandomString { public static void main(String[] args) { System.out.println( RandomString(16) ); } static String RandomString(int size) { String str1 = "abcdefghijklmnopqrstuvwxyz"; String str2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; String str3 = "0123456789"; // these are the valid charecters String valid = str1 + str2 + str3; Random random = new Random(); String mystring = ""; for( int i=0; i<size; i++ ) { int randnum = random.nextInt(valid.length()); mystring = mystring + valid.charAt(randnum); } return mystring; } }
Output:
$ java RandomString XGgsYI60JuJHeTr6