Java Random String | Generate random Strings

In this article, you will learn about Java random strings. There are multiple ways to generate random strings using Java programming. Here, you will see some simple ways and easy ways with examples to generate it using plain core Java.

You will learn the following types of random Strings:

  1. Random Alphabetic String
  2. Random Alpha-Numeric String
  3. Random Alpha-Numeric String should not start with a Number
  4. Random String in some Patterns
  5. Random UUID String

Generate random alphabetic String of a given length in Java

In this example, we are going to generate a random alphabetic string of a given size in Java using Math.random() method and Math.floor() method.

The random() is a static method of Math class generating a random double value between 0.0 to 1.0, and the floor() is also a static method, that rounds the specified double value downward and returns it. The rounded value will be equal to an integer number.

Approach to generate random alphabetic String of specific length:

  1. Take all alphabetic characters (total 52 with upper/lower case) in a string. eg.- “ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz“.
  2. Declare a string to hold the random string.
  3. Find a random integer (index) using the random() and floor() methods.
  4. Pick a character from allAlpha at the index position using the charAt() method.
  5. Concatenate the character into a random string variable.
  6. Repeat steps 3 to 5 until the given length using a loop.
  7. Finally, return the generated random string.

Let’s see the Java program for it below:

package com.javacodepoint.miscellaneous;

/*
 * Generate Random Strings
 */
public class GenerateRandomString {

	/*
	 * Generate random alphabetic String
	 */
	public static String generateRandom(int length) {

		// Total 52 characters (Alphabets in lower/upper case)
		String allAlpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

		// Declare a variable to hold random String
		String randomId = "";

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

			// Generate random integer in range 0 to 51
			int randomIndex = (int) Math.floor(52 * Math.random());

			// Get specified character and concat to randomId
			randomId += allAlpha.charAt(randomIndex);
		}

		// Finally return the randomId
		return randomId;
	}

	public static void main(String[] args) {

		// Generate alphabetic strings of specific length
		System.out.println("Alphabetic Random Strings:");
		System.out.println("A random string of 5 Characters => " + generateRandom(5));
		System.out.println("A random string of 10 Characters => " + generateRandom(10));
		System.out.println("A random string of 20 Characters => " + generateRandom(20));

	}

}

OUTPUT:

Alphabetic Random Strings:
A random string of 5 Characters => ZMolT
A random string of 10 Characters => REaTcPKdbP
A random string of 20 Characters => XbZQMgotYLAHeJxZoJUC

Generate random alpha-numeric String in Java

In this example, we include the numbers (0-9) also. eg.- “ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789“.

Approach to generate random alpha-numeric String of specific length:

  1. Take all alpha-numeric characters (total 62) in a string.
  2. Declare a string to hold the random string.
  3. Find a random integer (index) using the random() and floor() methods.
  4. Pick a character from allAlphaNumeric at the index position using the charAt() method.
  5. Concatenate the character into a random string variable.
  6. Repeat steps 3 to 5 until the given length using a loop.
  7. Finally, return the generated random string.

The only difference here is we included numbers (0-9) also to make all alpha-numeric characters. Let’s see the java program for it below:

package com.javacodepoint.miscellaneous;

/*
 * Generate Random String
 */
public class GenerateRandomString2 {

	/*
	 * Generate random alpha-numeric String
	 */
	public static String generateRandom(int length) {

		// Total 62 characters (Alphabets in lower/upper case and Numbers)
		String allAlphaNumeric = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

		// Declare a variable to hold random String
		String randomId = "";

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

			// Generate random integer in range 0 to 61
			int randomIndex = (int) Math.floor(62 * Math.random());

			// Get specified character and concat to randomId
			randomId += allAlphaNumeric.charAt(randomIndex);
		}

		// Finally return the randomId
		return randomId;
	}

	public static void main(String[] args) {

		// Generate alpha-numeric strings of specific length
		System.out.println("Alpha-Numeric Random Strings:");
		System.out.println("A random string of 5 Characters => " + generateRandom(5));
		System.out.println("A random string of 10 Characters => " + generateRandom(10));
		System.out.println("A random string of 20 Characters => " + generateRandom(20));

	}

}

OUTPUT:

Alpha-Numeric Random Strings:
A random string of 5 Characters => 3Xd5P
A random string of 10 Characters => EIyKDtZras
A random string of 20 Characters => p1XTxnWQy59zReZBZodM

Generate random alpha-numeric String should not start with a Number

In this example, we use all alpha-numeric characters. eg.- “ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789“. Here, the generated random string should not start with a number, to avoid it, we will pick the first character from index 0-51 only.

The approach to generate a random alpha-numeric String should not start with a number:

  1. Take all alpha-numeric characters (total 62) in a string.
  2. Declare a string to hold the random string.
  3. Initialize the first character for the random string. eg. allAlphaNumeric.charAt((int) Math.floor(52 * Math.random()));
  4. Find a random integer (index) using the random() and floor() methods.
  5. Pick a character from allAlphaNumeric at the index position using the charAt() method.
  6. Concatenate the character into a random string variable.
  7. Repeat steps 3 to 5 until the given length using a loop and the loop starts from index 1.
  8. Finally, return the generated random string.

The only difference here is we included numbers (0-9) also to make all alpha-numeric characters. Let’s see the Java program for it below:

package com.javacodepoint.miscellaneous;

/*
 * Generate Random Strings
 */
public class GenerateRandomString3 {

	/*
	 * Generate alpha-numeric string, without starting with number
	 */
	public static String generateRandom(int length) {

		// Total 62 characters (Alphabets in lower/upper case and Numbers)
		String allAlphaNumeric = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

		// Declare a variable to hold random String
		String randomId = "";

		// Pick first alphabet character only
		randomId += allAlphaNumeric.charAt((int) Math.floor(52 * Math.random()));

		// Start loop from 1
		for (int i = 1; i < length; i++) {

			// Generate random integer in range 0 to 61
			int randomIndex = (int) Math.floor(62 * Math.random());

			// Get specified character and concat to randomId
			randomId += allAlphaNumeric.charAt(randomIndex);
		}

		// Finally return the randomId
		return randomId;
	}

	public static void main(String[] args) {

		// Generate alpha-numeric strings but should not starts with a number
		System.out.println("Alpha-Numeric Random Strings without starting with number:");
		System.out.println("A random string of 5 Characters => " + generateRandom(5));
		System.out.println("A random string of 10 Characters => " + generateRandom(10));
		System.out.println("A random string of 20 Characters => " + generateRandom(20));

	}

}

OUTPUT:

Alpha-Numeric Random Strings without starting with a number:
A random string of 5 Characters => Jy4YD
A random string of 10 Characters => Oab0qfRB6P
A random string of 20 Characters => qYhuN4J29fUxA5Vh7SL2

Generate a random String in a specific Pattern

In this example, we are going to generate random strings in some specific patterns. For example, orderId= “OD_6578400012”. Here for orderId, the pattern is OD_XXXXXXXXXX, meaning OD_ is a static prefix followed by 10 random digits. Let’s see the Java program below:

package com.javacodepoint.miscellaneous;

/*
 * Generate Random Strings
 */
public class GenerateRandomString4 {

	/*
	 * Generate random string in <OD_XXXXXXXXXX> Pattern
	 */
	public static String generateOrderId() {
		String orderId = "OD_";
		for (int i = 0; i < 10; i++) {

			// Generate random integer in range 0 to 9
			orderId += (int) Math.floor(10 * Math.random());
		}
		return orderId;
	}

	/*
	 * Generate random string in <TXN-XXXXXXXXXXXXXXX> Pattern
	 */
	public static String generateTransactionId() {
		String transacrionId = "TXN-" + generateRandom(15);
		return transacrionId;
	}

	/*
	 * Generate random string in specific length
	 */
	public static String generateRandom(int length) {

		// Total 62 characters (Alphabets in lower/upper case and Numbers)
		String allAlphaNumeric = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

		// Declare a variable to hold random String
		String randomId = "";

		// Pick first alphabet character only
		randomId += allAlphaNumeric.charAt((int) Math.floor(52 * Math.random()));

		// Start loop from 1
		for (int i = 1; i < length; i++) {

			// Generate random integer in range 0 to 61
			int randomIndex = (int) Math.floor(62 * Math.random());

			// Get specified character and concat to randomId
			randomId += allAlphaNumeric.charAt(randomIndex);
		}

		// Finally return the randomId
		return randomId;
	}

	public static void main(String[] args) {

		// Generate random string in some patterns
		System.out.println("Random order ids in Pattern (OD_XXXXXXXXXX):");
		System.out.println("A random order id1 => " + generateOrderId());
		System.out.println("A random order id2 => " + generateOrderId());
		System.out.println("A random order id3 => " + generateOrderId());

		System.out.println("Random transaction ids in Pattern (TXN-XXXXXXXXXXXXXXX):");
		System.out.println("A random transaction id1 => " + generateTransactionId());
		System.out.println("A random transaction id2 => " + generateTransactionId());
		System.out.println("A random transaction id3 => " + generateTransactionId());

	}

}

OUTPUT:

Random order ids in Pattern (OD_XXXXXXXXXX):
A random order id1 => OD_7681092110
A random order id2 => OD_4481939727
A random order id3 => OD_5591012716
Random transaction ids in Pattern (TXN-XXXXXXXXXXXXXXX):
A random transaction id1 => TXN-Q7voNeNbXVfnNtu
A random transaction id2 => TXN-SdFdr5SBaCVfLio
A random transaction id3 => TXN-hL3bladfxG8omN0

Generate random String UUID

In this example, we are going to generate a UUID string using randomUUID() method of java.util.UUID java class.

A UUID is a Universally Unique Identifier that represents a 128-bit value. The standard representation of UUID uses hex digits. for exampledaad4dd9-f487-4bbe-8fbd-08d608ea40e1

Let’s see the Java program for it below:

package com.javacodepoint.miscellaneous;

import java.util.UUID;

/*
 * Generate Random Strings (UUID)
 */
public class GenerateRandomString5 {

	/*
	 * Generate random UUID
	 */
	public static String generateUUID() {
		return UUID.randomUUID().toString();
	}

	public static void main(String[] args) {

		// Generate random UUIDs
		System.out.println("Random UUID Strings:");
		System.out.println("A random uuid String1 => " + generateUUID());
		System.out.println("A random uuid String2=> " + generateUUID());
		System.out.println("A random uuid String3=> " + generateUUID());

	}

}

OUTPUT:

Random UUID Strings:
A random uuid String1 => 0f1170d2-0e21-4b02-af46-91384b34d29d
A random uuid String2=> dcd7224f-f44b-49c1-87c3-7b6f363ce1f3
A random uuid String3=> c6436e35-9641-4c86-880d-b0c042dbeacc

Conclusion

This tutorial explained different implementation methods, we were able to generate random strings using plain Java. In these Java examples, we used java.lang.Math.random() method.

References:
java.lang.Math.random()

Java logical programs list


Java Basic Programs

Java String Programs

Java Programs based on the Collection Framework

Share with friends

Leave a Comment

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