How to Get Randomly Generated Passwords in Java


Lists of the characters that can be included in a password will be created, and this example will explain how to randomly assemble these characters together into a password.

Source Code

package com.beginner.examples;

import java.util.Random;

public class PasswordGeneratorExample {

	private static final String CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

	private static final String NUMS = "01234567890";

	private static final String OtherCHARS = "!@#$%&*()_+-=[]?";

	private static final String ALLCHARS = CHARS + NUMS + OtherCHARS;

	public static void main(String[] args) {
		PasswordGeneratorExample p = new PasswordGeneratorExample();
		
		System.out.println("All characters:"+ALLCHARS);

		// Print the password
		System.out.println("The resulting password:");
		
		System.out.println(p.getPassword(PasswordGeneratorExample.ALLCHARS));

		System.out.println(p.getPassword(PasswordGeneratorExample.ALLCHARS));

		System.out.println(p.getPassword(PasswordGeneratorExample.ALLCHARS));

		System.out.println(p.getPassword(PasswordGeneratorExample.ALLCHARS));

	}

	public String getPassword(String chars) {
		
		//To store passwords
		StringBuilder sb = new StringBuilder();
		
		//Create a random object to get random Numbers
		Random random = new Random();
		
		for (int i = 1; i <= 5; i++) {
			
			int index = random.nextInt(chars.length() - 1);

			sb.append(chars.charAt(index));

		}

		return sb.toString();
	}

}

Output:

All characters:abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890!@#$%&*()_+-=[]?
The resulting password:
P0nbI
5gUa4
*4hs6
B7S3e

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments