Skip to content

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); }
Code language: Java (java)

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); }
Code language: Java (java)

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); }
Code language: Java (java)

See also  The Power of Two (2) Table
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x