JAVA

How to generate a random alpha-numeric string?

JAVA - How to generate a random alpha-numeric string? Generate a random alpha numeric string whose length is the number of characters specified.
  • Generate a random alpha-numeric string whose length is the number of characters specified.
  • Characters will be chosen from the set of alpha-numeric characters.
  • Count is the length of random string to create.
Java Code
private static final String ALPHA_NUMERIC_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
public static String randomAlphaNumeric(int count) {
StringBuilder builder = new StringBuilder();
while (count-- != 0) {
int character = (int)(Math.random()*ALPHA_NUMERIC_STRING.length());
builder.append(ALPHA_NUMERIC_STRING.charAt(character));
}
return builder.toString();
}
  • To generate random alpha-numeric String objects
  • 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,
Java Code
import org.apache.commons.lang3.RandomStringUtils;
public class RandomString {
    public static void main(String[] args) {
   
  String string = RandomStringUtils.random(64, false, true);
  System.out.println("Random 0 = " + string);
    string = RandomStringUtils.randomAlphabetic(64);
  System.out.println("Random 1 = " + string);
Java Code

  string = RandomStringUtils.randomAscii(32);
  System.out.println("Random 2 = " + string);
   
  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 = `[email protected]|>’/JdI):yB9PD%[email protected] e!S*’
Random 3 = 18Rk2DkkD3bsksE2RCDDRbC1bDCDa1D1

How to create random string with random characters?

Java Code
import java.util.Random;
 
public class MyStringRandomGen {
 
    private static final String CHAR_LIST = 
        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    private static final int RANDOM_STRING_LENGTH = 10;
      
    public String generateRandomString(){
         
        StringBuffer randStr = new StringBuffer();
        for(int i=0; i<RANDOM_STRING_LENGTH; i++){
            int number = getRandomNumber();
            char ch = CHAR_LIST.charAt(number);
            randStr.append(ch);
 }
        return randStr.toString();
    }
Java Code
    private int getRandomNumber() {
        int randomInt = 0;
        Random randomGenerator = new Random();
        randomInt = randomGenerator.nextInt(CHAR_LIST.length());
        if (randomInt - 1 == -1) {
            return randomInt;
        } else {
            return randomInt - 1;
        }
    }
Java Code
 public static void main(String a[]){
        MyStringRandomGen msr = new MyStringRandomGen();
        System.out.println(msr.generateRandomString());
        System.out.println(msr.generateRandomString());
        System.out.println(msr.generateRandomString());
        System.out.println(msr.generateRandomString());
        System.out.println(msr.generateRandomString());
        System.out.println(msr.generateRandomString());
        System.out.println(msr.generateRandomString());
    }
}

Output:

UdX5PwalMI
qj62F7zuoR
ndJUNiHSlh
YohYpF5MfA
mwX9UhI7Ci
bCn5bsk2em
pzMXQDYaDx

READ  Java Programming - Program for Fibonacci numbers

Generates an alphanumeric string based on specified length :

Java Code
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class StringUtil {

  private static Random random = new Random((new Date()).getTime());
Java Code
 
    public static String generateRandomString(int length) {
      char[] values = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9'};
      String out = "";
      for (int i=0;i<length;i++) {
          int idx=random.nextInt(values.length);
        out += values[idx];
      }
      return out;
    }
  }

About the author

author

author

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

X