lang3

Generate random alphanumeric string

In this example we shall show you how to generate random alphanumeric String objects. We are using the org.apache.commons.lang3.RandomStringUtils class, that offers operations for random Strings. To generate random alphanumeric String objects one should perform the following steps:

  • Use random(int count, boolean letters, boolean numbers) method to create a random string whose length is the number of characters specified.
  • Use randomAlphabetic(int count) method to create a random string whose length is the number of characters specified.
  • Use randomAscii(int count) method to create a random string whose length is the number of characters specified.
  • Use random(int count, int start, int end, boolean letters, boolean numbers, char... chars) method to create a random string based on a variety of options, using default source of randomness,

as described in the code snippet below.  

package com.javacodegeeks.snippets.core;

import org.apache.commons.lang3.RandomStringUtils;
 
public class RandomString {
    
	public static void main(String[] args) {

  
		// Random string only with numbers

  String string = RandomStringUtils.random(64, false, true);

  System.out.println("Random 0 = " + string);
 

  // Random alphabetic string

  string = RandomStringUtils.randomAlphabetic(64);

  System.out.println("Random 1 = " + string);
 

  // Random ASCII string

  string = RandomStringUtils.randomAscii(32);

  System.out.println("Random 2 = " + string);
 

  // Create a random string with indexes from the given array of chars  

  string = RandomStringUtils.random(32, 0, 20, true, true, "bj81G5RDED3DC6142kasok".toCharArray());

  System.out.println("Random 3 = " + string);
    }
}

Output:

Random 0 = 0280748858014499019999655817886659056806824331462442367947839271
Random 1 = BdODmKWjGtaKeFyYsNCbOPRzquNIIRMiEFPjqTSgbfMvMeZgNKihEdUdUXUniHUh
Random 2 = `2G@|>'/JdI):yB9PD%S4sZp_@ e!S*'
Random 3 = 18Rk2DkkD3bsksE2RCDDRbC1bDCDa1D1

  
This was an example of how to generate random alphanumeric String objects in Java.

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button