I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE COURSE

In this article, we’re going to show how to generate a random String in Java – first using the standard Java libraries and the using the Apache Commons Lang library.

This article is part of the “Java – Back to Basic” series here on Baeldung.

1. Generate Random Unbounded String with Plain Java

Let’s start simple and generate a random String bounded to 7 characters:

@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);
}

Keep in mind that the new String will not be anything remotely alphanumeric.

2. Generate Random Bounded String with Plain Java

Next – let’s look at creating a more constrained random String; we’re 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);
}

3. 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);
}

So – instead of all the low-level code in the Java example – this one is done with a simple one-liner.

4. Generate Alphabetic String with Apache Commons Lang

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);
}

5. Generate Alphanumeric String with Apache Commons Lang

And finally – 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 you have it – creating bounded and unbounded Strings with either plain Java or the Apache Commons Library.

6. Conclusion

Through different implementation methods we were able to generate bound and unbound strings, using plain Java or the Apache Commons Library.

The implementation of all of these examples and snippets can be found in the GitHub project. This is a Maven-based project so it should be easy to import and run.

I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE LESSONS

  Subscribe  
newest oldest most voted
Notify of
c.press
Guest

should #2 actually be this:

int randomLimitedInt = leftLimit + (int) (new Random().nextFloat() * (rightLimit – leftLimit + 1));

Grzegorz Piwowarek
Guest

What does it change in this case?

c.press
Guest

it fixes this test
assertFalse(generatedString.indexOf(‘z’)==-1);

Grzegorz Piwowarek
Guest

Ok, sure. Thanks!