Generating Password using Java Program Example

Generating Password using Java

In this tutorial, I am sharing simple program snippet about, Generating Password using Java. The example Java Program were tested with environment and output is shared in the same post.

The following program is about Generating Password using Java. Password generation is common activity in many application. This sample code can be used in order to achieve the same in your application.

package com.dineshkrish.util;

 * @author Dinesh Krishnan

public class PasswordGenerator {

	// Defining Character Array you can change accordingly 
	private static final char[] charArray = { '1', 'A', 'a', 'B', 'b', 'C',
			'c', '2', 'D', 'd', 'E', 'e', 'F', 'f', '3', 'G', 'g', 'H', 'h',
			'I', 'i', 'J', 'j', 'K', 'k', 'L', 'l', '4', 'M', 'm', 'N', 'n',
			'O', 'o', '5', 'P', 'p', 'Q', 'q', 'R', 'r', 'S', 's', 'T', 't',
			'6', '7', 'U', 'u', 'V', 'v', 'U', 'u', 'W', 'w', '8', 'X', 'x',
			'Y', 'y', 'Z', 'z', '9' };

	// Method for generating the password
	public static String generate(int length) {

		String generatedPassword = "";

		final int minLength = 5; // Minimum Length
		final int maxLength = 20;// Maximum Length

		StringBuffer sb = new StringBuffer();

		if (length >= minLength && length <= maxLength) {
			int random = 0;
			for (int i = 0; i < length; i++) {
				// Getting Random Number with in range(ie: 60 total character present)
				random = (int) (Math.random() * (charArray.length - 1));
				sb.append(charArray[random]); // Appending the character using StringBuffer
			generatedPassword = String.valueOf(sb); // Assigning the Generated Password to String variable
		} else {

			// Error Message
			System.out.println("length should be >= "+minLength+" and <="+maxLength);
			System.exit(0); // Terminating Program if there is error.
		return generatedPassword;

	public static void main(String[] args) {

		String generatedPassword = generate(10); // Method calling
		System.out.println("Generated Password : "+generatedPassword);


Generated Password : TGXJ1K4n2B

Hello, folks, I am a founder of I love Java and Open source technologies, If you find my tutorials are useful, please consider making donations to these charities.