TL;DR – Generate random strings in Java with these easy-to-follow techniques. Perfect for developers of all levels!
In this article, you will learn to generate a random string using a variety of different libraries, I love the approach using the Apache Commons Lang library, it’s so simple and effective, using a single line you can do many things in the code, anyway let’s move ahead!
Let’s deep dive for different available ways to generate a random String in java.
Cover Photo Credits: Photo by Author | Generate Random String in java
1. Generate Random Alphabetic String With Java 8
let’s use Random.ints
— added in JDK 8 — to generate an alphabetic String,
@Test public void givenUsingJava8_whenGeneratingRandomAlphabeticString_thenCorrect() { int leftLimit = 97; // letter 'a' int rightLimit = 122; // letter 'z' int targetStringLength = 10; Random random = new Random(); String generatedString = random.ints(leftLimit, rightLimit + 1) .limit(targetStringLength) .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); System.out.println(generatedString); }
2. Generate Random Alphanumeric String With Java 8
We can widen our character set to get an alphanumeric String.
@Test public void givenUsingJava8_whenGeneratingRandomAlphanumericString_thenCorrect() { int leftLimit = 48; // numeral '0' int rightLimit = 122; // letter 'z' int targetStringLength = 10; Random random = new Random(); String generatedString = random.ints(leftLimit, rightLimit + 1) .filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97)) .limit(targetStringLength) .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); System.out.println(generatedString); }
3. Generate Random Unbounded String With Plain Java
Generate 7 letters random string using unbounded String,
@Test public void givenUsingPlainJava_whenGeneratingRandomStringUnbounded_thenCorrect() { byte[] array = new byte[7]; // length is bounded by 7 new Random().nextBytes(array); String generatedString = new String(array, Charset.forName("UTF-8")); System.out.println(generatedString); }
4. Generate Random Bounded String With Plain Java
Now we will create a more constrained random string;
We are going to generate a random String using lowercase alphabetic letters and a set length,
@Test public void givenUsingPlainJava_whenGeneratingRandomStringBounded_thenCorrect() { int leftLimit = 97; // letter 'a' int rightLimit = 122; // letter 'z' int targetStringLength = 10; Random random = new Random(); StringBuilder buffer = new StringBuilder(targetStringLength); for (int i = 0; i < targetStringLength; i++) { int randomLimitedInt = leftLimit + (int) (random.nextFloat() * (rightLimit - leftLimit + 1)); buffer.append((char) randomLimitedInt); } String generatedString = buffer.toString(); System.out.println(generatedString); }
5. Generate Bounded Random String With Apache Commons Lang
The Commons Lang library from Apache helps a lot with random string generation. Let’s take a look at generating a bounded String using only letters,
@Test public void givenUsingApache_whenGeneratingRandomStringBounded_thenCorrect() { int length = 10; boolean useLetters = true; boolean useNumbers = false; String generatedString = RandomStringUtils.random(length, useLetters, useNumbers); System.out.println(generatedString); }
6. Generate Alphabetic String With Apache Commons Lang [Very Popular]
Another very simple example — this time a bounded String with only alphabetic characters, but without passing boolean flags into the API,
@Test public void givenUsingApache_whenGeneratingRandomAlphabeticString_thenCorrect() { String generatedString = RandomStringUtils.randomAlphabetic(10); System.out.println(generatedString); }
7. Generate Alphanumeric String With Apache Commons Lang
The same random bounded String but this time — numeric
@Test public void givenUsingApache_whenGeneratingRandomAlphanumericString_thenCorrect() { String generatedString = RandomStringUtils.randomAlphanumeric(10); System.out.println(generatedString); }
And there we have it — creating bounded and unbounded strings with either plain Java, a Java 8 variant, or the Apache Commons Library.
Important Note:
In these Java examples, we’ve used java.util.Random, but one point worth mentioning is that it is not cryptographically secure. Consider using java.security.SecureRandom instead for security-sensitive applications.
Hope you find this article helpful, Please share your thoughts in the comment section!
I obtain an immense amount of satisfaction from helping others attain their goals and reach their potential through technology. Even if you wish to reach out and say "Hello", I sincerely appreciate all of the wonderful correspondence I receive each day from readers. You all enrich my life, and I hope I am able to do the same for you all as well.
If you find joy and value in what I do, please consider supporting my work with a donation — however much you can afford, it means and helps more than you can imagine.
You can give tips too using Buy me a coffee.
Discover more from 9Mood
Subscribe to get the latest posts sent to your email.
0 Comments