Java Generating Random Strings

Java Generating Random Strings | On this page, we will see different ways to generate random string in Java. To generate a random string we can use a random class present in the Java library.

We will see how to generate a random string in Java with the help of randomUUID() method, and how to generate a random string in Java having uppercase, lowercase, numbers, and special characters. And later we see develop a program to generate a random Base64 string in Java.

Java Generating Random Strings using randomUUID()

The randomUUID() method defined in the UUID class is a static factory to retrieve a type 4 (pseudo-randomly generated) UUID. The UUID is generated using a cryptographically strong pseudo-random number generator.

import java.util.UUID;

public class Main {
   public static void main(String args[]) {
      UUID uuid = UUID.randomUUID();
      String randomString = uuid.toString();
      System.out.println("Random string: " + randomString);
   }
}

Here are some output examples of generating random string using randomUUID():-

Random string: 409962da-daeb-4685-87b9-47db2354e266

Random string: 0eff811c-cf51-4b74-a774-9a4680d8cc00

Random string: cc383d27-b030-4f98-a60a-ba13c3b23800

Random string: 8ead83a3-43b8-4af3-9c04-ba4623e1d8ba

Java Random String Generator Program

In the below program, we have taken all uppercase characters from A-Z and a string of length 9. We have used random class methods to pick any character from A-Z and add it to the newly generated string.

import java.util.Random;

public class Main {
   public static void main(String[] args) {
      String string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

      StringBuilder strbuilder = new StringBuilder();
      Random rand = new Random();
      int length = 9;

      for (int i = 0; i < length; i++) {
         int index = rand.nextInt(string.length());
         char randomChar = string.charAt(index);
         strbuilder.append(randomChar);
      }

      String randomString = strbuilder.toString();
      System.out.println("Random String is: " + randomString);
   }
}

Output:-

Random String is: CSHDDVOIU

Random String is: HHZIOKWRL

Random String is: JWFRCALFU

In the above program, we took only uppercase characters, hence the generated strings contain only uppercase characters. In the below program, we will take uppercase, lowercase, and numbers to generate the string.

Java Generating Random Strings – Alphanumeric String

import java.util.Random;

public class Main {
   public static void main(String[] args) {
      String string1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
      String string2 = string1.toLowerCase();
      // Or, String string2 = "abcdefghijklmnopqrstuvwxyz";
      String string3 = "0123456789";

      // create alphanumeric string
      String alphaNumeric = string1 + string2 + string3;

      StringBuilder strbuilder = new StringBuilder();
      Random rand = new Random();
      int length = 10;
      for (int i = 0; i < length; i++) {
         int index = rand.nextInt(alphaNumeric.length());
         strbuilder.append(alphaNumeric.charAt(index));
      }

      String randomString = strbuilder.toString();
      System.out.println("Random String is: " + randomString);
   }
}

Output:-

Random String is: iSIA0iasDh

Random String is: 79LmFdFKOL

Random String is: oTdJTWpbhw

If you want some special characters in the generated string then declare a string variable after the “string3” variable and initialize it with some special characters. And add that string to “alphaNumeric”.

Generate Random Base64 String Java

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Random;

public class Main {
   public static String generateBase64String() {
      String str = generateString();
      try {
         return Base64.getEncoder()
          .encodeToString(str.getBytes(StandardCharsets
          .UTF_8.toString()));
      } catch (UnsupportedEncodingException ex) {
         throw new RuntimeException(ex);
      }
   }

   private static String generateString() {
      String uppercaseChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
      String lowercaseChars = uppercaseChars.toLowerCase();
      String numbers = "0123456789";
      String specialChars = 
                  " !\"\'#$%&()*+,-./:;<=>?@[\\]^_`{|}~";
      String string = uppercaseChars + lowercaseChars + 
                      numbers + specialChars;

      StringBuilder strbuilder = new StringBuilder();
      Random rand = new Random();
      int length = 16;
      for (int i = 0; i < length; i++) {
         int index = rand.nextInt(string.length());
         strbuilder.append(string.charAt(index));
      }

      return strbuilder.toString();
   }

   public static void main(String[] args) {
      System.out.println("Random Base64 String is: " 
                        + generateBase64String());
   }
}

Output:-

Random Base64 String is: Q3diKGRMaG8zPlldT2JHLg==

Random Base64 String is: MipLMj50IVR0SyBkXVJjeQ==

Random Base64 String is: QnFHMnE3dDAqbkApXHR2dA==

In the above program to generate a random base64 string Java, first, we have defined a generateString() method to generate a random string. The generateString() method will generate a random string of length of 16 characters and it can contain uppercase characters, lowercase characters, numbers, and special characters which are allowed to use within a password. See- List of special characters for the password.

After that, we defined a generateBase64String() method which internally calls generateString() to get a random string, and then we converted them into Base64.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *