Java: Generate random character string

This java code snippet generates a random character string of a random length from 1 to 9 inclusive.

import java.util.Random;

public class Main {

	public static void main(String args[])
	{
		String alphabet= "abcdefghijklmnopqrstuvwxyz";
		String s = "";
		Random random = new Random();
		int randomLen = 1+random.nextInt(9);
		for (int i = 0; i < randomLen; i++) {
		    char c = alphabet.charAt(random.nextInt(26));
		    s+=c;
		}
		
		System.out.println(s);
	}
}

Search within Codexpedia

Custom Search

Search the entire web

Custom Search