Skip to content

Instantly share code, notes, and snippets.

@imrichardcole
Created June 7, 2013 19:01
Show Gist options
  • Save imrichardcole/5731570 to your computer and use it in GitHub Desktop.
Save imrichardcole/5731570 to your computer and use it in GitHub Desktop.
Create a random alphanumeric String in Java
public class StringsAndThings {
private static final char[] characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
private static final Random random = new Random(new Date().getTime());
public static void main(String[] args) {
final String randomString = StringsAndThings.createRandomString(1000);
System.out.println(randomString);
}
private static String createRandomString(int length) {
final StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < length; i++) {
String randomValue;
if (random.nextInt(2) == 1) {
randomValue = String.valueOf(random.nextInt(10));
} else {
randomValue = Character.toString(characters[random.nextInt(26)]);
}
stringBuffer.append(randomValue);
}
return stringBuffer.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment