Generating Random Strings with Apache Commons Lang | Generated by AI

Home PDF

RandomStringUtils is a highly useful class from the Apache Commons Lang library that provides various static methods for generating random strings. This includes generating strings with specific lengths, containing only letters, only numbers, alphanumeric characters, or even from a custom set of characters.

Here’s how to use it and the necessary Maven dependency:

How to use org.apache.commons.lang3.RandomStringUtils;

First, you need to import the class in your Java file:

import org.apache.commons.lang3.RandomStringUtils;

Then you can use its static methods. Here are some common examples:

  1. Generate a random alphanumeric string of a specific length:

    String randomAlphaNumeric = RandomStringUtils.randomAlphanumeric(10);
    System.out.println("Random alphanumeric: " + randomAlphaNumeric); // e.g., "aB5cY2x9Pq"
    
  2. Generate a random alphabetic string of a specific length:

    String randomAlphabetic = RandomStringUtils.randomAlphabetic(8);
    System.out.println("Random alphabetic: " + randomAlphabetic); // e.g., "GhJkLmNo"
    
  3. Generate a random numeric string of a specific length:

    String randomNumeric = RandomStringUtils.randomNumeric(6);
    System.out.println("Random numeric: " + randomNumeric); // e.g., "123456"
    
  4. Generate a random string with a mix of letters and numbers, specifying flags:

    String randomLettersAndNumbers = RandomStringUtils.random(12, true, true);
    System.out.println("Random letters and numbers: " + randomLettersAndNumbers); // e.g., "abC123DeF456"
    
  5. Generate a random string from a custom set of characters:

    String chars = "abcdefg";
    String randomFromCustomSet = RandomStringUtils.random(5, chars);
    System.out.println("Random from custom set: " + randomFromCustomSet); // e.g., "gcfae"
    

What library to use in pom.xml

To use RandomStringUtils in a Maven project, you need to add the commons-lang3 dependency to your pom.xml file.

Here’s the dependency snippet:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.14.0</version> </dependency>

Important Notes:


Back 2025.06.24 Donate