Java Program to Create random strings


In this article, we will understand how to create random strings. String is a datatype that contains one or more characters and is enclosed in double quotes(“ ”).

Below is a demonstration of the same −

Suppose our input is

The size of the string is defined as: 10

The desired output would be

Random string: ink1n1dodv

Algorithm

Step 1 - START
Step 2 - Declare an integer namely string_size, a string namely alpha_numeric and an object of StringBuilder namely string_builder.
Step 3 - Define the values.
Step 4 - Iterate for 10 times usinf a for-loop, generate a random value using the function Math.random() and append the value using append() function.
Step 5 - Display the result
Step 6 - Stop

Example 1

Here, we bind all the operations together under the ‘main’ function.

public class RandomString {
   public static void main(String[] args) {
      int string_size = 10;
      System.out.println("The size of the string is defined as: " +string_size);
      String alpha_numeric = "0123456789" + "abcdefghijklmnopqrstuvxyz";
      StringBuilder string_builder = new StringBuilder(string_size);
      for (int i = 0; i < string_size; i++) {
         int index = (int)(alpha_numeric.length() * Math.random());
         string_builder.append(alpha_numeric.charAt(index));
      }
      String result = string_builder.toString();
      System.out.println("The random string generated is: " +result);
   }
}

Output

The size of the string is defined as: 10
The random string generated is:
ink1n1dodv

Example 2

Here, we encapsulate the operations into functions exhibiting object-oriented programming.

public class RandomString {
   static String getAlphaNumericString(int string_size) {
      String alpha_numeric = "0123456789" + "abcdefghijklmnopqrstuvxyz";
      StringBuilder string_builder = new StringBuilder(string_size);
      for (int i = 0; i < string_size; i++) {
         int index = (int)(alpha_numeric.length() * Math.random());
         string_builder.append(alpha_numeric.charAt(index));
      }
      return string_builder.toString();
   }
   public static void main(String[] args) {
      int string_size = 10;
      System.out.println("The size of the string is defined as: " +string_size);
      System.out.println("The random string generated is: ");
      System.out.println(RandomString.getAlphaNumericString(string_size));
   }
}

Output

The size of the string is defined as: 10
The random string generated is:
ink1n1dodv

Updated on: 29-Mar-2022

523 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements