How to generate a random alpha-numeric string in java

How to generate a random alpha-numeric string in java

To generate a random alpha-numeric string in Java, you can use the Random class to create random characters and append them to a StringBuilder or StringBuffer. Here's a simple example:

import java.util.Random; public class RandomAlphaNumericGenerator { private static final String ALPHA_NUMERIC_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; public static String generateRandomString(int length) { StringBuilder stringBuilder = new StringBuilder(); Random random = new Random(); for (int i = 0; i < length; i++) { int index = random.nextInt(ALPHA_NUMERIC_STRING.length()); char randomChar = ALPHA_NUMERIC_STRING.charAt(index); stringBuilder.append(randomChar); } return stringBuilder.toString(); } public static void main(String[] args) { int length = 10; // Specify the desired length of the random string String randomString = generateRandomString(length); System.out.println("Random Alpha-Numeric String: " + randomString); } } 

In this example, the generateRandomString method generates a random alpha-numeric string of the specified length. It uses a StringBuilder to build the string character by character, with each character randomly selected from the ALPHA_NUMERIC_STRING containing the set of allowed characters (uppercase letters and digits).

You can adjust the length variable to change the length of the generated string as needed.


More Tags

32-bit excel-interop vimeo dead-reckoning google-finance activation listeners regexp-substr run-script thinktecture-ident-server

More Java Questions

More Animal pregnancy Calculators

More Organic chemistry Calculators

More Stoichiometry Calculators

More Housing Building Calculators