Java Program to Create random strings

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Java program to generate a random string

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

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.