Monday, January 25, 2016

Java - How to generate random alpha-numeric strings

In this tutorial, we will show you how to get a random string using three methods in the examples bellow. Generation of random characters in Java does not exist, but there are several ways to do that. We will use java.util.Random.nextInt () method to generate random integers and then convert those integers to the conrresponding character according to the ASCII code.

Generate type character

The ASCII code of the first character is lowercase alphabetic 65 (a) and the last is 97 + 26 = 122 (z). The generated number is in the interval [97, 122] or in the range [0.26] + 97.

Random rand = new Random();
char c = (char)(rand.nextInt(26) + 97);
System.out.println(c);

Generate random string

For n characters, you need to use for loop:

public static void main(String[] args) {

   Random rand = new Random();
   String str="";
   for(int i = 0 ; i < 15 ; i++){
       char c = (char)(rand.nextInt(26) + 97);
       str += c;
       System.out.print(c+" ");
   }
}
q v r i v g z a w b b d n x y 

Generate alpha-numeric string from a set

This example show how to generate alphanumeric characters from a defined set of characters. Proceed as follows:
  • Create a String with all that you want
  • Get the length of this string
  • Call Rand.nextInt() method that returns the random length between 0 and n.
  • Print out the char using alphabet.charAt (k) method

Random rand = new Random();
String set = "abcd1235";
int length = set.length();
for(int i = 0; i < 20; i++) {
   int k = rand.nextInt(length);
   System.out.print(set.charAt(k)+" ");
}
d 5 1 b 1 b 2 3 c a b b 5 5 d d b 2 c 3 
References:
How to generate a random String in Java
Java doc: java.util.Random class
Extended ascii code

No comments:

Post a Comment