Random Password Generator in Java
A random password generator is commonly used in real-world applications such as account creation, password reset systems, and security tools.
In this program, we generate a strong password by combining uppercase letters, lowercase letters, digits, and special characters.
Password Generation Rules
The generated password will:
- Contain uppercase letters (A–Z)
- Contain lowercase letters (a–z)
- Contain digits (0–9)
- Contain special characters
- Have a user-defined length
Example
Input: Password Length = 10
Output: A9@kP3#xT2
Logic Explanation
- Create a string containing all allowed characters.
- Use Java’s
Randomclass to generate random indexes. - Select characters randomly from the allowed set.
- Repeat until the desired password length is reached.
Java Program to Generate Random Password
import java.util.Random;
import java.util.Scanner;
public class RandomPasswordGenerator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter password length: ");
int length = sc.nextInt();
String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String lower = "abcdefghijklmnopqrstuvwxyz";
String digits = "0123456789";
String special = "!@#$%^&*()_+-={}[]|:;<>,.?/";
String allChars = upper + lower + digits + special;
Random random = new Random();
String password = "";
for (int i = 0; i < length; i++) {
int index = random.nextInt(allChars.length());
password = password + allChars.charAt(index);
}
System.out.println("Generated Password: " + password);
}
}
Sample Output
Enter password length: 12
Generated Password: A@9kL3#xP7!Q
Important Notes
- Password strength increases with length.
- Each run generates a different password.
- Characters may repeat.
Practice Challenges
- Ensure at least one uppercase, lowercase, digit, and special character.
- Generate password without repeating characters.
- Allow user to choose which character sets to include.
- Generate multiple passwords at once.
Random password generation is a practical application of strings, random numbers, and security concepts in Java.