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()
Leave a Reply