How to Generate a Random String in Java


Java provides many ways to generate random strings.

1. Using Apache Commons

public void generatingRandomAlphanumericString_ApacheCommons() {
    String generatedString = RandomStringUtils.randomAlphanumeric(10);
    System.out.println(generatedString);
}

2. Using Java 8

public void generatingRandomAlphanumericString_Java8() {
    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. Using Plain Java

public void generatingRandomStringUnbounded_PlainJava() {
    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);
}