How to Generate a Random String in Java using Apache Commons Lang
Join the DZone community and get the full member experience.Join For Free
In a previous post, we had shared a small function that generated random string in Java. It turns out that similar functionality is available from a class in the extremely useful apache commons lang library.
If you are using maven, download the jar using the following dependency:
<dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>20030203.000129</version> </dependency>
The class we are interested in is RandomStringUtils. Listed below are some functions you may find useful.
- Generate and print a random string of length 5 from all characters available
- Generate and print random string of length 10 from upper and lower case alphabets
- Generate and print a random number of length 12
- Generate and print a random string of length 5 using only a, b, c and d characters
Published at DZone with permission of Faheem Sohail, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.