• Register
140 points
4

In this article, I will explain how to generate a random string in java. Refer to the below example for your reference.

Approach

  • What we’re going to do is use the random class to generate characters that we have set and then we will be having that string.
  • Import the Random class, present in Random package. Now list the characters that we are going to use. Create a string of a preferred name which makes it accessible for making this random string.
  • Create an empty string variable and next create a random object. We need to set the length of that random string we are willing for.
  • I have created five characters length random string in this example. You can change it if you want to.
  • Create a character array to create a random string of length of five characters. A for loop is used to add those individual characters into the character array to make the random string.
  • Inside the loop, make the character array equals the length of the random character at a particular index. This basically represents the length of the total string input taken.
  • Now we need to convert this array of characters into a string by using again a for a loop. Finally, print the random string obtained.

Program

import java.util.Random;

public class RandomStringDemo 

{

public static void main(String[] args)

{

String characters = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”;

String randString = “ “;

Random rand = new Random();

int length = 4;

 // int length = rand.nextInt(20); // Produces random strings of different lengths

Char[] alpha = new char[length];

for(int i=0;i<length;i++)

{

alpha[i] = characters.charAt(rand.nextInt(characters.length()));

}

for (int i=0;i<alpha.length;i++)

{

randString +=alpha[i];

}

System.out.println(randString);

}

}

Output

KODL
140 points
4