Example 1: Java program to generate a random string
import java.util.Random;
class Main {
public static void main(String[] args) {
// create a string of all characters
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// create random string builder
StringBuilder sb = new StringBuilder();
// create an object of Random class
Random random = new Random();
// specify length of random string
int length = 7;
for(int i = 0; i < length; i++) {
// generate random index number
int index = random.nextInt(alphabet.length());
// get character specified by index
// from the string
char randomChar = alphabet.charAt(index);
// append the character to string builder
sb.append(randomChar);
}
String randomString = sb.toString();
System.out.println("Random String is: " + randomString);
}
}
Output
Random String is: IIYOBRK
In the above example, we have first created a string containing all the alphabets. Next, we have generated a random index number using the nextInt()
method of the Random
class.
Using the random index number, we have generated the random character from the string alphabet. We then used the StringBuilder
class to append all the characters together.
If we want to change the random string into lower case, we can use the toLowerCase()
method of the String
.
randomString.toLowerCase()
Note: The output will be different every time you run the program.
Example 2: Java Program to generate a random alphanumeric string
import java.util.Random;
class Main {
public static void main(String[] args) {
// create a string of uppercase and lowercase characters and numbers
String upperAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String lowerAlphabet = "abcdefghijklmnopqrstuvwxyz";
String numbers = "0123456789";
// combine all strings
String alphaNumeric = upperAlphabet + lowerAlphabet + numbers;
// create random string builder
StringBuilder sb = new StringBuilder();
// create an object of Random class
Random random = new Random();
// specify length of random string
int length = 10;
for(int i = 0; i < length; i++) {
// generate random index number
int index = random.nextInt(alphaNumeric.length());
// get character specified by index
// from the string
char randomChar = alphaNumeric.charAt(index);
// append the character to string builder
sb.append(randomChar);
}
String randomString = sb.toString();
System.out.println("Random String is: " + randomString);
}
}
Output
Random Alphanumeric String is: pxg1Uzz9Ju
Here, we have created a string that contains numbers from 0 to 9 and the alphabets in uppercase and lowercase.
From the string, we have randomly generated an alphanumeric string of length 10.