Java - Write code to get Random String

Requirements

Write code to get Random String

Demo

//package com.book2s;

import java.util.Random;

public class Main {
    public static void main(String[] argv) {
        int length = 42;
        System.out.println(getRandomString(length));
    }/*from   w w  w.j  a  v a2  s . co  m*/

    private static final String charset = "!0123456789abcdefghijklmnopqrstuvwxyz";
    private static Random rand;

    public static String getRandomString(int length) {
        if (rand == null) {
            rand = new Random(System.currentTimeMillis());
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int pos = rand.nextInt(charset.length());
            sb.append(charset.charAt(pos));
        }
        return sb.toString();
    }

}

Related Exercise