tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Articles > Java > Basics > How to generate a Random String in Java

How to generate a Random String in Java 

The following example shows generating a random string in java.

File Name  :  
com/bethecoder/articles/basics/random/RandomStringTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.articles.basics.random;

import java.util.Random;

public class RandomStringTest {

  /**
   @param args
   */
  public static void main(String[] args) {

    System.out.println(getRandomString(6));
    System.out.println(getRandomString("123"6));
    
    System.out.println(getRandomString("xyz"8));
    System.out.println(getRandomString("abc123"8));
  }

  public static String getRandomString(int length) {
    return getRandomString("abcdefghijklmnopqrstuvwxyz", length);
  }
  
  public static String getRandomString(String allowedChars, int length) {
    if (allowedChars == null || allowedChars.trim().length() == || length <= 0) {
      throw new IllegalArgumentException("Please provide valid input");
    }
    
    Random rand = new Random();
    StringBuilder sb = new StringBuilder();
    
    for (int i = ; i < length ; i ++) {
      sb.append(allowedChars.charAt(rand.nextInt(allowedChars.length())));
    }
    return sb.toString();
  }
}
   

It gives the following output,
snammo
132121
yxxzyxzx
aabbc21a



 
  


  
bl  br