Wednesday, April 25, 2012

Java: Generate random numeric, alphabetic and alphanumeric numbers

In java many times you may require to generate random numbers. Random number could be numeric, alphabetic or both alphanumeric. Let’s see a java program which generates random numbers. You can also customize length of the number. Directly you can run the below codes and see the output no need to add any jar files.

About the example:

We have 3 methods randomAlphabetic(), randomNumeric() and randomAlphanumeric() which generates alphabetic, numeric and alphanumeric numbers respectively. Just provide the length of the number and see the output. Let’s see the self explanatory code.


/* RandomNumber.java */

import java.util.Random;

public class RandomNumber {

 private static final Random RANDOM = new Random();
 
 private String random(int length, boolean num,boolean alpha) {
  
  StringBuffer result = new StringBuffer();
  char c = 0;

  int min = 48;
  int max = 90;

  int i=0;

  while(i<length) {

   c = (char) (RANDOM.nextInt(max - min) + min);

   if((num && Character.isDigit(c)) || 
   (alpha && Character.isLetter(c)) || 
   (num && alpha && Character.isLetterOrDigit(c))) {
    result.append(c);
    i++;
   }
  }   
  return result.toString();  
 }
 
 //Function to generate only alphabetic numbers
 public String randomAlphabetic(int length) {
  
   return random(length,false,true);
  }
 
 //Function to generate only numeric numbers
  public String randomNumeric(int length) {
  
   return random(length,true,false);
  }
  
 //Function to generate alphanumeric numbers
  public String randomAlphanumeric(int length) {
   
   return random(length,true,true);
  }

 public static void main(String[] args) {

  RandomNumber obj = new RandomNumber();
  
  System.out.println(obj.randomAlphabetic(5));
  System.out.println(obj.randomNumeric(10));
  System.out.println(obj.randomAlphanumeric(15));

 }

}

Note : If you want to generate random unique numbers just add it to Set to make sure that all numbers are unique.