import java.util.Random;
public class RandomStringGenerator {
public static void main(String[] args) {
int length = 10; // The length of the random string
String randomString = generateRandomString(length);
System.out.println(randomString);
}
public static String generateRandomString(int length) {
String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
int index = random.nextInt(characters.length());
sb.append(characters.charAt(index));
}
return sb.toString();
}
}
IMyWI9Yh2V
generateRandomString()
method, which takes an integer argument length
and returns a random string of length length
.generateRandomString()
method generates a random string by randomly selecting characters from a string containing all uppercase and lowercase letters and digits. It uses a Random object to generate random
integers, which are used to select characters from the string. The StringBuilder
class is used to construct the random string character by character.generateRandomString()
method returns the constructed 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);
}
}
Random String is: IWPAJZJ
nextInt()
method of the Random
class.StringBuilder
class to append all the characters together.toLowerCase()
method of the String
.randomString.toLowerCase()​