random String with digit and letter - Java java.util

Java examples for java.util:Random String

Description

random String with digit and letter

Demo Code


//package com.java2s;

public class Main {
    public static String randomString(int length) {
        StringBuffer buf = new StringBuffer();
        for (int counter = 0; counter < length; counter++) {
            buf.append(randomChar());/*  w  w w  .  j a v a2s. c o  m*/
        }
        return buf.toString();
    }

    private static char randomChar() {
        if (Math.random() > 0.5) {
            return (char) ((int) '0' + random(0, 9));
        } else {
            return (char) ((int) 'A' + random(0, 25));
        }
    }

    public static int random(int min, int max) {
        assert (min <= max);
        return min + (int) Math.round(Math.random() * (double) (max - min));
    }

    public static Object random(Object values[]) {
        assert (values != null);
        return values[random(0, values.length - 1)];
    }
}

Related Tutorials