Random Password Generator in Java — Rules, Examples and Program

Learn how to generate a secure random password in Java using uppercase letters, lowercase letters, digits, and special characters with customizable length.

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:

Example

Input: Password Length = 10

Output: A9@kP3#xT2

Logic Explanation

  1. Create a string containing all allowed characters.
  2. Use Java’s Random class to generate random indexes.
  3. Select characters randomly from the allowed set.
  4. 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

Practice Challenges

  1. Ensure at least one uppercase, lowercase, digit, and special character.
  2. Generate password without repeating characters.
  3. Allow user to choose which character sets to include.
  4. Generate multiple passwords at once.

Random password generation is a practical application of strings, random numbers, and security concepts in Java.