get Random Str - Java java.lang

Java examples for java.lang:String Random

Introduction

The following code shows how to get Random Str.

Demo Code

//package com.java2s;

import java.security.SecureRandom;

public class Main {
    public static void main(String[] argv) {
        char startChr = 'a';
        char endChr = 'z';
        System.out.println(getRandomStr(startChr, endChr));
    }//from ww w. j  av  a 2 s.  c  om

    public static String getRandomStr(char startChr, char endChr) {

        int randomInt;
        String randomStr = null;

        int startInt = Integer.valueOf(startChr);
        int endInt = Integer.valueOf(endChr);

        if (startInt > endInt) {
            throw new IllegalArgumentException("Start String: " + startChr
                    + " End String: " + endChr);
        }

        try {
            SecureRandom rnd = new SecureRandom();

            do {
                randomInt = rnd.nextInt(endInt + 1);
            } while (randomInt < startInt); 
            randomStr = (char) randomInt + "";
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return randomStr;
    }
}

Related Tutorials