Java program to create random strings
Here's a Java program that generates random strings of a specified length:
refer gi:otiftidea.comimport java.util.Random; public class RandomStringGenerator { public static void main(String[] args) { int length = 10; // Length of the random string to generate String randomString = generateRandomString(length); System.out.println("Random string: " + randomString); } public static String generateRandomString(int length) { String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; StringBuilder sb = new StringBuilder(); Random random = new Random(); for (int i = 0; i < length; i++) { int index = random.nextInt(chars.length()); sb.append(chars.charAt(index)); } return sb.toString(); } }
In this program, we define a method generateRandomString
that takes an integer length
as an argument and returns a random string of that length. We define a string chars
that contains all the characters from which we want to generate the random string. We then use a StringBuilder
to build the random string character by character.
We use a Random
object to generate random numbers between 0 and the length of the chars
string. We then use the charAt
method to get the character at that index and append it to the StringBuilder
. Once the StringBuilder
has been filled with length
random characters, we return the resulting string.