Wednesday, November 24, 2010

Generate a random alpha-numeric string in Java

By combinig use of Char array that having alphabets and numbers are an string of alphanumberic characters we can generate random alpha numberic strings in java.here is the exampls code that generate random alpha numberic string for the given length.

 /**
     * Generates alpha numeric random number for the given length.
     * for this it accounts lowercase alpha characters(a-z) and numbers(0-9)
     * @param length length of the alpha numeric random to be generated.
     * @return resulting random alpha numeric string for the given length.
     */
    public static String getAlphaNumbericRandom(int length) {
        //include lower case alpha(a-z) and numbers(0-9)
        String chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        int numberOfCodes = 0;//controls the length of alpha numberic string
        String code = "";
        while (numberOfCodes < length) {
            char c = chars.charAt((int) (Math.random() * chars.length()));
            code += c;
            numberOfCodes++;
        }
        System.out.println("Code is :" + code);
        return code;
    }

If we want to create 6 digit apha numberic random means we have call getAlphaNumbericRandom methods as

getAlphaNumbericRandom(6);

No comments:

Post a Comment