We can make use of the String that holds all the characters that can be a part of the random string to be generated and make use of the java.util.Random class to generate the random string based on the length required.
Program:import java.util.Random;
/**
* Code2care Java Examples
*
* Generate Random String
*
*/
public class JavaRandomStringExample {
public static void main(String[] args) {
JavaRandomStringExample jrs = new JavaRandomStringExample();
System.out.println(jrs.generateRamdonString(15));
System.out.println(jrs.generateRamdonString(25));
System.out.println(jrs.generateRamdonString(35));
System.out.println(jrs.generateRamdonString(45));
}
public String generateRamdonString(int size) {
String digits = "ABCDEFGHIJKLMNOPQRSTUVWZYZabcdefghijklmnopqrstuvwxyz0123456789";
int sizeOfRandomString = size;
StringBuilder randomString = new StringBuilder();
for(int i=1;i<=sizeOfRandomString;i++) {
Random random = new Random();
int position = random.nextInt(digits.length());
randomString = randomString.append(digits.charAt(position));
}
return randomString.toString();
}
}
Output:
7pgxqwiR1TEhZJB
kJexTSwpP6pt6kbTY22LhFxFC
m2kySQF7QLx1JGLR9Kz3CCPHkBFircEE9Jt
esMtxgqWd31UbokPwWqAwqu8sak5aJYTpYyoKdPZYH5q6
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!