Java – generate random String

In this tutorial, we will see how to generate random String in java.
There are many ways to generate random String.Let’s explore some of ways to generate random String.

Using simple java code with Random

You can use SecureRandom class to generate random String for you.
Let’s understand with the help of example.

Output:

Generating String of length 10: Hz0hHRcO6X
Generating String of length 10: wSnjx6HNlv
Generating String of length 10: 4Wg9Iww0Is
Generating String of length 8: EdJmSrfC
Generating String of length 8: dAifHyQG
Generating String of length 8: HNnxieWg
Generating String of length 7: hQrqQ2L
Generating String of length 7: 0BWBtYI
Generating String of length 7: 3WStHON

Using Apache Common lang

You can use Apache Common lang to generate random String. It is quite easy to generate random String as you can use straight forward APIs to create random String.

Create AlphaNumericString

You can use RandomStringUtils.randomAlphanumeric method to generate alphanumeric random strn=ing.

Output:

Generating String of length 10: Wvxj2x385N
Generating String of length 10: urUnMHgAq9
Generating String of length 10: 8TddXvnDOV

Create random Alphabetic String

You can use RandomStringUtils.randomAlphabetic method to generate alphanumeric random strn=ing.

Output:

Generating String of length 10: zebRkGDuNd
Generating String of length 10: RWQlXuGbTk
Generating String of length 10: mmXRopdapr

That’s all about generating Random String in java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *