Compute a random string composed of lower case letters and numbers. - Java java.lang

Java examples for java.lang:String Random

Description

Compute a random string composed of lower case letters and numbers.

Demo Code


//package com.java2s;

import java.util.Random;

public class Main {
    public static void main(String[] argv) {
        int length = 42;
        System.out.println(computeRandomString(length));
    }//w ww. ja va 2  s.co  m

    /**
     * Compute a random string composed of lower case letters and numbers.
     *
     * @param length
     * the length of the random String
     * @return a random String
     */
    public static String computeRandomString(final int length) {
        Random r = new Random(); // just create one and keep it around
        String alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append(alphabet.charAt(r.nextInt(alphabet.length())));
        }
        String randomName = sb.toString();
        return randomName;
    }
}

Related Tutorials