Generate a random string using java.util.Random

Posted By : Manish Gupta | 25-Jan-2018

In this blog, we will see the use of java.util.Random class to generate a random string. Generating a random string can be very useful ranging from creating a random password for small desktop applications to generating the salts to create a strong password. In the below snippet, I have created a method getRandomString(int) that takes the length of the random string and returns a random string.

 

In this method I have defined the characters that can become the part of the randomly generated string of the length entered by the user. Every time user executes this snippet, he/she will get the different sequence of characters. For example: If user wants to have a string of 5 characters then this snippent will produce a string of 5 characters which can contain any of the characters from the (A-Z) or (a-z) or (0-9) or some special characters.

import java.util.Random;
import java.util.Scanner;

public class RandomString
{
   private static String getRandomString( int length )
   {
	  //specify the character set that you want for your randomString 
      String upperCase_characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";   // upper-case letters
      String lowerCase_characters = "abcdefghijklmnopqrstuvwxyz";   // lower-case letters
      String numbers = "0123456789";  // digits
      String specialCharacters = "@#$&";  // special chacaters
      
      String randomString = "";
      String source = upperCase_characters + lowerCase_characters + numbers + specialCharacters;
      Random randomGenerator = new Random();
       for(int i=0; ijavac RandomString.java

C:\Users\User1\Desktop>java RandomString
Enter the length of random string you want:
6
A randomly generated string of length 6 is LJH3jS

C:\Users\User1\Desktop>java RandomString
Enter the length of random string you want:
7
A randomly generated string of length 7 is q&AbcG8
***********************************************************

To know more in detail about the java.util.Random, visit https://docs.oracle.com/javase/7/docs/api/java/util/Random.html#next(int)

 

--------- Thanks ---------

About Author

Author Image
Manish Gupta

Manish is a Java Developer with hands on experience in Core Java, JSP, Spring framework, JavaScript, JQuery, HTML, CSS, and SQL/PL-SQL. Tools used: Eclipse, Netbeans, DBeaver, Oracle SQL Developer, Toad, MS SQL Server. He is a keen learner and technology

Request for Proposal

Name is required

Comment is required

Sending message..