skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Saturday, October 6, 2012

Random String ID

Posted by Raju Gupta at 1:05 AM – 0 comments
 
A random String id of specified length is generated as follows:
A set of valid characters is stored in a string.
From this set randomly 10 characters are selected and an Id is formed.
import java.util.Random;

public class XUIDGenerator 
{
    private static final int NUM_CHARS = 10;
    private static String    chars     = "abcdefghijklmonpqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static Random    r         = new Random();


    public static String getUniqueID() 
    {
        char[] buf = new char[NUM_CHARS];

        for (int i = 0; i < buf.length; i++)
        {
            buf[i] = chars.charAt(r.nextInt(chars.length()));
        }

        return new String(buf);
    }

    public static void main(String[] args) 
   {
        System.out.println(XUIDGenerator.getUniqueID());
    }
}

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger