Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How to Generate a Random String in Java using Apache Commons Lang

DZone's Guide to

How to Generate a Random String in Java using Apache Commons Lang

· Integration Zone ·
Free Resource

The State of API Integration 2018: Get Cloud Elements’ report for the most comprehensive breakdown of the API integration industry’s past, present, and future.

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
    
    System.out.println(RandomStringUtils.random(5));
  • Generate and print random string of length 10 from upper and lower case alphabets
    
    System.out.println(RandomStringUtils.randomAlphabetic(10));
  • Generate and print a random number of length 12
    
    System.out.println(RandomStringUtils.randomNumeric(12));
  • Generate and print a random string of length 5 using only a, b, c and d characters
    
    System.out.println(RandomStringUtils.random(10,new char[]{'a','b','c','d'}));
    




Your API is not enough. Learn why (and how) leading SaaS providers are turning their products into platforms with API integration in the ebook, Build Platforms, Not Products from Cloud Elements.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}