Java - Write code to get Random String by length

Requirements

Write code to get Random String by length

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  va  2  s.  co  m

    private static final String RANDOM_CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public static String getRandomString(int length) {
        if (length <= 0)
            return null;

        StringBuffer sb = new StringBuffer();
        Random r = new Random();
        int range = RANDOM_CHARS.length();
        for (int i = 0; i < length; i++) {
            sb.append(RANDOM_CHARS.charAt(r.nextInt(range)));
        }
        return sb.toString();
    }
}