Best Ways to Generate Random String in Java

Various and effective ways to generate random String for your project requirements1 min


learn java generate a random string with multiple ways

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.

adsense


Discover more from 9Mood

Subscribe to get the latest posts sent to your email.


Like it? Share with your friends!

What's Your Reaction?

Lol Lol
0
Lol
WTF WTF
0
WTF
Cute Cute
0
Cute
Love Love
0
Love
Vomit Vomit
0
Vomit
Cry Cry
0
Cry
Wow Wow
0
Wow
Fail Fail
0
Fail
Angry Angry
0
Angry
Rakshit Shah

Legend

Hey Moodies, Kem chho ? - Majama? (Yeah, You guessed Right! I am from Gujarat, India) 25, Computer Engineer, Foodie, Gamer, Coder and may be a Traveller . > If I can’t, who else will? < You can reach out me by “Rakshitshah94” on 9MOodQuoraMediumGithubInstagramsnapchattwitter, Even you can also google it to see me. I am everywhere, But I am not God. Feel free to text me.

0 Comments

Leave a Reply

Choose A Format
Story
Formatted Text with Embeds and Visuals
List
The Classic Internet Listicles
Ranked List
Upvote or downvote to decide the best list item
Open List
Submit your own item and vote up for the best submission
Countdown
The Classic Internet Countdowns
Meme
Upload your own images to make custom memes
Poll
Voting to make decisions or determine opinions
Trivia quiz
Series of questions with right and wrong answers that intends to check knowledge
Personality quiz
Series of questions that intends to reveal something about the personality
is avocado good for breakfast? Sustainability Tips for Living Green Daily Photos Taken At Right Moment