1. Overview
In this tutorial, we're going to look at how we can generate a random String in Java. We'll look at the solutions that are readily available in JDK and also the ones that come with external libraries.
2. Use Random
Firstly, we'll examine an approach that relies on java.util.Random class:
public void randomUsingPlain(int length) {
final Random random = new Random();
final byte[] array = new byte[length];
random.nextBytes(array);
final String generated = new String(array, StandardCharsets.UTF_8);
System.out.println(generated);
}
Here, we're creating a Random instance that populates a byte array. Note that we're initializing the array with the given length. After we have the byte array populated, we're creating a String from it using UTF-8.
One important note is that the resulting String can contain any character - not limited to numbers or Latin alphabetic characters:
멠Å^@-;
3. Use Stream with Random
Another approach relying on java.util.Random uses its Stream support.
public void randomUsingStreams(int length) {
final int start = '0';
final int end = 'z';
final Random random = new Random();
final String generated = random.ints(start, end + 1)
.filter(i -> Character.isLetter(i) || Character.isDigit(i))
.limit(length)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
System.out.println(generated);
}
Here, we're using Random.ints method to emit integers in the range from '0'=48 to 'z'=122. Then the emitted integers are filtered further to get an alphanumeric String.
The resulting String will contain only the numbers and Latin alphabetic characters - 0-9, a-z and A-Z:
vjZP8
4. Use UUID
So far, we have generated random Strings with a given length. If the length isn't a requirement for us, java.util.UUID is a good way to generate a random String:
public void randomUsingUuid() {
System.out.println(UUID.randomUUID().toString());
}
The resulting String will be a hexadecimal representation of the UUID, containing 0-9, a-f, or A-F:
8b963686-4eb0-44ac-be6f-e6cee0890e64
5. Use Apache Commons
Next, we'll look at the RandomStringUtils class from Apache Common Lang library:
public void randomUsingCommons(int length) {
System.out.println(RandomStringUtils.random(length));
}
Here, RandomStringUtils.random returns a String that can contain any character i.e. 懧𥸨䂼䯱.
But it also allows us to specify the permitted characters:
System.out.println(RandomStringUtils.random(length, "abcdefghij"));
Additionally, it offers some convenience methods:
public void randomUsingCommons(int length) {
System.out.println(RandomStringUtils.randomAlphabetic(length));
System.out.println(RandomStringUtils.randomAlphanumeric(length));
System.out.println(RandomStringUtils.randomNumeric(length));
}
- randomAlphabetic returns a random String composed of Latin alphabetic characters.
- randomAlphanumeric returns a random String containing only the numbers and Latin alphabetic characters.
- randomNumeric return a String composed of only numbers:
VCbmt
xn7O0
58782
6. Use Apache Commons Text
Lastly, we'll examine the org.apache.commons.text.RandomStringGenerator class from Apache Commons Text.
The important point is that RandomStringGenerator enables us to control the generation process in a fine-grained manner:
public void randomUsingCommonsText(int length) {
final org.apache.commons.text.RandomStringGenerator generatorWithRange = new org.apache.commons.text.RandomStringGenerator.Builder()
.withinRange('0', 'z')
.filteredBy(CharacterPredicates.LETTERS, CharacterPredicates.DIGITS)
.build();
System.out.println(generatorWithRange.generate(length));
final org.apache.commons.text.RandomStringGenerator generatorWithSelection = new org.apache.commons.text.RandomStringGenerator.Builder()
.selectFrom("abcdefghij".toCharArray())
.build();
System.out.println(generatorWithSelection.generate(length));
}
Here, we're firstly generating our random String from a given character range after applying a filter. Then we're generating another String from the given permitted characters.
7. Summary
In this tutorial, we covered some common techniques to generate a random String.
Firstly, we looked at the JDK-based solutions that require no additional library. Then we examined others that rely on Apache Commons libraries.
Finally, check out the source code for all examples over on Github.