random string generator java code example

Example 1: java random string

public static String getRandomString(int size) {
  	// The string that we will return
	String rand = "";
  	// The chars that are used to generate the random string
	String chars = "1234567890-=!@#$%^&*()_+qwertyuiop[]\\QWERTYUIOP{}|asdfghjkl;'ASDFGHJKL:\"zxcvbnm,./ZXCVBNM<>?";
  	// Loop based on the requested size
  	for (int i = 0; i < size; i++) {
      	// Add a random char from the chars string to the rand string
		rand += chars.toCharArray()[new Random().nextInt(chars.length())];
	}
  	// Return the random string
	return rand;
}

Example 2: generate 5 digit random string in java

RandomStringUtils.randomAlphanumeric(17).toUpperCase()

Example 3: java 8 random string generator

@Test
public void givenUsingJava8_whenGeneratingRandomAlphanumericString_thenCorrect() {
    int leftLimit = 48; // numeral '0'
    int rightLimit = 122; // letter 'z'
    int targetStringLength = 10;
    Random random = new Random();
 
    String generatedString = random.ints(leftLimit, rightLimit + 1)
      .filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97))
      .limit(targetStringLength)
      .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
      .toString();
 
    System.out.println(generatedString);
}

Example 4: random string generator java

import java.util.Random;

public class Generator {
	public static String generateRandomPassword(int len) {
		String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijk"
          +"lmnopqrstuvwxyz!@#$%&";
		Random rnd = new Random();
		StringBuilder sb = new StringBuilder(len);
		for (int i = 0; i < len; i++)
			sb.append(chars.charAt(rnd.nextInt(chars.length())));
		return sb.toString();
	}
}

Tags:

Misc Example