Generating random strings is a very common need of software applications. For examples, random strings are used for identifiers, tokens, keys, one-time passwords, verification code, etc. So in this article, I’d love to share with you some ways and code examples which you can use to generate random strings in Java, that include alphabetic, alphanumeric, numeric-only, and special characters.

 

1. Generate Random Strings using Java Core

For simple purposes (no strict security requirement), you can write some code with plain Java code. No external dependencies needed.

 

The basic logic about generating random string

The following code snippet gives you a basic idea about the logic of generating random strings in Java:

public static String randomStringSimple(int length) {
	byte[] byteArray = new byte[length];
	Random random = new Random();
	random.nextBytes(byteArray);

	return new String(byteArray, Charset.forName("UTF-8"));
}
This method generates a random string whose size is specified by the parameter length. You can see, we use the Random class’ nextBytes() method that returns a byte array filled with random values. Then we create a String object from the byte array, which results in a random string.

Since a byte can have any value from -128 to 127, the generated string can contain non-visible characters. That means this code example cannot be used in practice, rather it gives you the basic idea of how to write code for generating random strings in Java.

Also note that the java.util.Random class generates pseudorandom numbers, or fake random.

 

Generate alphanumeric random string using Java Core



The following code example shows how to generate a random string which contains both alphabetic and numeric characters:

public static String randomAlphanumericString(int length) {
	String alphanumericCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuv";

	StringBuffer randomString = new StringBuffer(length);
	Random random = new Random();

	for (int i = 0; i < length; i++) {
		int randomIndex = random.nextInt(alphanumericCharacters.length());
		char randomChar = alphanumericCharacters.charAt(randomIndex);
		randomString.append(randomChar);
	}

	return randomString.toString();
}
The logic in this code is quite simple. First we define a String object alphanumericCharacters that contains all letters and numbers. Then we generate a random String with each character is randomly chosen from the predefined set. You can see we use the Random class’ nextInt() method that returns a random integer number that is not greater than the specified bound.

And below is some testing code that generates 3 random strings with different length:

String randomString1 = randomAlphanumericString(10);
System.out.println("Random String #1: " + randomString1);

String randomString2 = randomAlphanumericString(15);
System.out.println("Random String #2: " + randomString2);

String randomString3 = randomAlphanumericString(20);
System.out.println("Random String #3: " + randomString3);
Sample output:

Random String #1: X7OsqoYB8P
Random String #2: pED6RK7HIVTOq0W
Random String #3: fqihhIIHsarlY4UAukXk
 

Generate random strings include special characters

You can modify the above code example to generate random strings that contain both alphanumeric and special characters. Based on the character codes in ASCII table:

ascii table

You see, the codes from 33 to 126 includes special, alphabetic and numeric characters. So below is the code:

public static String randomAlphanumericString(int length) {
	char startChar = 33;
	char endChar = 126;

	StringBuffer randomString = new StringBuffer(length);
	Random random = new Random();

	for (int i = 0; i < length; i++) {
		int randomIndex = startChar + random.nextInt(endChar - startChar + 1);
		randomString.append((char) randomIndex);
	}

	return randomString.toString();
}
Usage code:

String randomString1 = randomAlphanumericString(10);
System.out.println("Random String #1: " + randomString1);

String randomString2 = randomAlphanumericString(15);
System.out.println("Random String #2: " + randomString2);

String randomString3 = randomAlphanumericString(20);
System.out.println("Random String #3: " + randomString3);
And sample output:

Random String #1: !`;u!k=|Vc
Random String #2: %%xB\B25ryhg|zS
Random String #3: K/IzJ'}e@z$Vo%`'.Il)
You can use this code example to generate random strong passwords.


2. Generate Random Strings using UUID Class

You can use the java.util.UUID class to generate random strings that are kind of Universally Unique Identifier (UUID). Below is an example code:

UUID uuid1 = UUID.randomUUID();
System.out.println("UUID #1: " + uuid1);

UUID uuid2 = UUID.randomUUID();
System.out.println("UUID #2: " + uuid2);

UUID uuid3 = UUID.randomUUID();
System.out.println("UUID #3: " + uuid3);
Sample output:

UUID #1: f7f56e8b-888b-400b-819f-c987059a861b
UUID #2: 430330c4-7cc4-4d26-82bc-ddb005eab5f5
UUID #3: 8a0d450d-90a4-4ae6-90ef-978b9ce4f93e
The UUID strings look like serial keys or product keys, right? So you can use UUID to ensure the uniqueness of random strings.


3. Generate Random Strings using Apache Commons Lang

If you don’t want to write code from scratch, you can use a ready-made library such as Apache Commons Lang - a popular library that provides extra methods missing in the standard Java libraries. To use Apache Commons Lang in a Java Maven project, declare the following dependency in the pom.xml file:

<dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-lang3</artifactId>
	<version>3.12.0</version>
</dependency>
Then you can use some randomXXX() methods in the RandomStringUtils class for generate a kind of random string you wish to.

Basically, you can use the generic method random(int count, boolean letters, boolean numbers). For example, the following code generates a 10-character random string that includes both letters and numbers:

boolean useLetters = true;
boolean useNumbers = true;

String randomString = RandomStringUtils.random(10, useLetters, useNumbers);
You can use the random(count) method to generate a random string that contains any characters. For example:

String randomString = RandomStringUtils.random(10);
Use the randomAscii(count) method to generate a random string that contains only ASCII characters (code from 32 to 126). For example:

String randomAscii = RandomStringUtils.randomAscii(8);
Use the randomAlphabetic(count) method to generate a random string that contains only letters. For example:

String randomAlphabetic = RandomStringUtils.randomAlphabetic(20);
Use the randomAlphanumeric(count) method to generate a random string that contains both letters and numbers. For example:

String randomAlphanumeric = RandomStringUtils.randomAlphanumeric(20);
And use the randomNumeric(count) method to generate a random string that contains only numbers. For example:

String randomNumeric = RandomStringUtils.randomNumeric(6);
So, depending on your need, use an appropriate method provided by the RandomStringUtils class. It’s very convenient if your project is already making use of the Apache Commons Lang library.

 

4. Use Secure and Thread-safe Random Generator

In case more security is required, you should use SecureRandom class instead of Random, which provides a cryptographically strong random number generator. For example:

Random random = new SecureRandom();
And in the random string generation code is used by multiple threads, you should use the ThreadLocalRandom class. For example:

Random random = ThreadLocalRandom.current();
That’s my guide and code examples about generating random strings in Java. I hope you find this article helpful. Thanks for reading.

 

References:

 

Other Java Coding Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment

   


Comments 

#1hafid nur2023-02-06 08:48
thank you for your article
Quote