Write a Java Program to Create random strings

Generating random strings is a common task in many applications, such as generating random passwords, unique identifiers, or testing data.

In this tutorial, we will explore how to create random strings using Java.


Java provides a built-in class called “Random” that generates random numbers.

We can use this class to generate random strings by creating a string of random characters.

Here’s an example:

import java.util.Random;

public class RandomStringGenerator {
   public static void main(String[] args) {
       int length = 10;
       String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
       StringBuilder sb = new StringBuilder();
       Random random = new Random();
       for (int i = 0; i < length; i++) {
           int index = random.nextInt(chars.length());
           sb.append(chars.charAt(index));
       }
       String randomString = sb.toString();
       System.out.println("Random String: " + randomString);
   }
}

In the above code, we first specify the length of the random string we want to generate.

We also define a string that contains all the characters that we want to use for the random string.

In this case, we use uppercase and lowercase letters, as well as digits.

We then create a StringBuilder object that we will use to construct the random string.

We also create an instance of the Random class, which we will use to generate random numbers.

Next, we loop through the length of the random string and select a random character from the characters string.

We use the nextInt() method of the Random class to generate a random index that we use to select a character from the characters string.

We then append the selected character to the StringBuilder object.

After the loop, we convert the StringBuilder object to a String using the toString() method and print the resulting random string.

We can modify the above code to generate random strings with different character sets or lengths.

We can also use libraries such as Apache Commons Lang or Guava to generate random strings with more advanced options.


In conclusion, generating random strings in Java is a simple task that can be achieved using the Random class and a loop to select random characters from a predefined set of characters.

This technique can be used in various applications, such as generating random passwords or testing data.

Editorial Team
Editorial Team

Programming Cube website is a resource for you to find the best tutorials and articles on programming and coding.