Java Random create random String example 6

Description

Java Random create random String example 6

import java.util.Random;

public class Main {

   public static void main(String[] args) {

      System.out.println(getRandomString(10));
      System.out.println(getRandomString(20));
   }/*from   w  w w  . jav  a 2 s.com*/

   public static String getRandomString(int length) {
      final String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJLMNOPQRSTUVWXYZ1234567890 !@#$%^&*()_+";
      StringBuilder result = new StringBuilder();
      while (length > 0) {
         Random rand = new Random();

         result.append(characters.charAt(rand.nextInt(characters.length())));
         length--;
      }
      return result.toString();
   }
}



PreviousNext

Related