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.

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