How to Generate Random String with Random Characters in Java


The example will prompt user to put all the characters in a string variable and then create the Random object.Here is an example of a randomly obtained string of length 8.

Source Code

package com.beginner.examples;

import java.util.Random;

public class GetRandomString {

	private static String strs1 = "abcdefghijklmnopqrstuvwxyz";

	private static String strs2 = strs1.toUpperCase();

	// All characters, you can add other characters
	private static String allStr = strs1 + strs2;

	public static void main(String[] args) {

		//Get random strings five times in a row
		for (int i = 1; i <= 5; i++) {

			String randomStr = getRandomStr();

			System.out.println(i+". Get a random string:" + randomStr);

		}

	}
	/**
	 * This method gets random strings
	 */
	public static String getRandomStr() {
		//Create random objects
		Random random = new Random();
		
		//Create a string object to hold the results
		String randomStr = new String();

		for (int i = 0; i < 8; i++) {
			
			int randomIndex = random.nextInt(allStr.length() - 1);

			randomStr += allStr.charAt(randomIndex);
		}

		return randomStr;

	}
}

Output:

1. Get a random string:TnKuHnVO
2. Get a random string:NlbznnkN
3. Get a random string:YUFopReR
4. Get a random string:nAvAbQnG
5. Get a random string:dKcjcUwP

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments