Back to Java
2026-03-146 min read

Password Generator (Java)

Learn Password Generator (Java) step by step with clear examples and exercises.

Title: Password Generator (Java)

Why This Matters

today, securing your online accounts is essential. A strong password is vital to protect against unauthorized access and data breaches. However, creating unique and complex passwords can be challenging for many users. That's where a Password Generator comes in handy. In this lesson, we will build a Java-based Password Generator that creates secure passwords with ease.

In this full guide, we will delve deeper into the concepts of creating a robust and flexible Password Generator using Java. We will cover the prerequisites needed to understand the code, explore the core concept in detail, discuss common mistakes to avoid, provide practice questions for further learning, and answer frequently asked questions.

Prerequisites

To follow along with this lesson, you should have a basic understanding of the following topics:

  1. Java programming fundamentals (variables, loops, functions)
  2. Java Scanner class for user input
  3. Random number generation in Java
  4. Character encoding and ASCII values
  5. Exception handling to manage invalid user inputs
  6. Understanding of classes and objects in Java
  7. Familiarity with Java's String manipulation methods
  8. Knowledge of Java's collections framework (e.g., ArrayList, HashMap)
  9. Understanding of interfaces and enumerations
  10. Comfortable navigating the Java Standard Library documentation

Core Concept

A Password Generator is a simple application that generates random passwords based on specific criteria such as length, character types (uppercase letters, lowercase letters, numbers, special characters), and exclusion of certain characters. In our Java implementation, we will create a custom class PasswordGenerator with a method generatePassword().

Here's an outline of the steps involved in building the Password Generator:

  1. Define character sets for uppercase letters, lowercase letters, numbers, and special characters as ArrayLists.
  2. Create a method to generate random characters from each set using Java's Collections framework.
  3. Combine the generated character sets into a single password string.
  4. Optionally, allow users to specify password length, character types, and exclude certain characters.
  5. Provide an easy-to-use interface for generating passwords.
  6. Implement exception handling for invalid user inputs.
  7. Optimize the Password Generator for better performance (e.g., reducing random character generation).
  8. Create a custom enumeration CharacterType to represent different character sets.
  9. Use interfaces and abstract classes to create reusable components, such as CharacterSet and PasswordGeneratorFactory.
  10. Implement unit tests for the Password Generator to ensure correct functionality.

Worked Example

Let's dive into the code and create a simple Password Generator in Java.

import java.util.*;
import java.util.Random;
import java.util.Scanner;
import java.util.function.Supplier;

public class PasswordGenerator {
private static final String UPPERCASE_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String LOWERCASE_CHARS = "abcdefghijklmnopqrstuvwxyz";
private static final String NUMBERS = "0123456789";
private static final String SPECIAL_CHARS = "@#$%^&*()_+-=[]{}|;:,.<>?/~`";

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter password length (min 4, max 16): ");
int length = scanner.nextInt();
if (length < 4 || length > 16) {
throw new IllegalArgumentException("Invalid password length. Please enter a value between 4 and 16.");
}

System.out.print("Include uppercase letters? (y/n): ");
boolean includeUppercase = scanner.next().equalsIgnoreCase("y");

System.out.print("Include lowercase letters? (y/n): ");
boolean includeLowercase = scanner.next().equalsIgnoreCase("y");

System.out.print("Include numbers? (y/n): ");
boolean includeNumbers = scanner.next().equalsIgnoreCase("y");

System.out.print("Include special characters? (y/n): ");
boolean includeSpecialChars = scanner.next().equalsIgnoreCase("y");

System.out.print("Exclude any specific characters? (e.g., !@#$%^&*():;<>?/|{}[] ,.+-=) : ");
List<Character> excludedChars = new ArrayList<>();
Scanner excludeScanner = new Scanner(System.in);
String input = excludeScanner.nextLine();
for (char c : input.toCharArray()) {
if (!c == ',' && !Character.isWhitespace(c)) {
excludedChars.add(c);
}
}

PasswordGeneratorFactory factory = new PasswordGeneratorFactory();
PasswordGenerator passwordGen = factory.createPasswordGenerator(includeUppercase, includeLowercase, includeNumbers, includeSpecialChars, excludedChars);
String password = passwordGen.generatePassword(length);
System.out.println("Generated Password: " + password);
}

// ... (rest of the code)
}

// Custom enumeration for character types
enum CharacterType {
UPPERCASE, LOWERCASE, NUMBERS, SPECIAL_CHARS;
}

// Interface for character sets
interface CharacterSet {
List<Character> getCharacters();
}

// Concrete implementation of character sets
class UppercaseCharacterSet implements CharacterSet {
@Override
public List<Character> getCharacters() {
return new ArrayList<>(Arrays.asList(UPPERCASE_CHARS.toCharArray()));
}
}

class LowercaseCharacterSet implements CharacterSet {
@Override
public List<Character> getCharacters() {
return new ArrayList<>(Arrays.asList(LOWERCASE_CHARS.toCharArray()));
}
}

class NumberCharacterSet implements CharacterSet {
@Override
public List<Character> getCharacters() {
return new ArrayList<>(Arrays.asList(NUMBERS.toCharArray()));
}
}

class SpecialCharacterSet implements CharacterSet {
@Override
public List<Character> getCharacters() {
return new ArrayList<>(Arrays.asList(SPECIAL_CHARS.toCharArray()));
}
}

// Factory class for creating PasswordGenerator instances
class PasswordGeneratorFactory {
private final Map<CharacterType, Supplier<CharacterSet>> characterSets;

public PasswordGeneratorFactory() {
characterSets = new HashMap<>();
characterSets.put(CharacterType.UPPERCASE, UppercaseCharacterSet::new);
characterSets.put(CharacterType.LOWERCASE, LowercaseCharacterSet::new);
characterSets.put(CharacterType.NUMBERS, NumberCharacterSet::new);
characterSets.put(CharacterType.SPECIAL_CHARS, SpecialCharacterSet::new);
}

public PasswordGenerator createPasswordGenerator(boolean includeUppercase, boolean includeLowercase, boolean includeNumbers, boolean includeSpecialChars, List<Character> excludedChars) {
List<CharacterSet> characterSets = new ArrayList<>();
if (includeUppercase) {
characterSets.add(characterSets.get(CharacterType.UPPERCASE));
}
if (includeLowercase) {
characterSets.add(characterSets.get(CharacterType.LOWERCASE));
}
if (includeNumbers) {
characterSets.add(characterSets.get(CharacterType.NUMBERS));
}
if (includeSpecialChars) {
characterSets.add(characterSets.get(CharacterType.SPECIAL_CHARS));
}

for (CharacterSet set : characterSets) {
set.getCharacters().removeIf(ch -> excludedChars.contains(ch));
}

return new PasswordGenerator(characterSets);
}
}

// Custom PasswordGenerator class with improved structure and reusable components
class PasswordGenerator {
private final List<CharacterSet> characterSets;
private final Random random;

public PasswordGenerator(List<CharacterSet> characterSets) {
this.characterSets = characterSets;
this.random = new Random();
}

// ... (rest of the generatePassword() method and other methods)
}

Common Mistakes

  1. Forgetting to import necessary classes (e.g., java.util.Random, java.util.Scanner)
  2. Not handling invalid user input (e.g., password length outside the specified range)
  3. Neglecting to include at least one character set in the generated password
  4. Failing to check if a randomly chosen character is allowed based on user preferences and excluded characters
  5. Not using the getRandomCharPercentage() method for generating random characters from all sets
  6. Not optimizing the Password Generator for better performance (e.g., reducing random character generation)
  7. Not properly handling exceptions for invalid user inputs
  8. Forgetting to close Scanner objects after use
  9. Using hardcoded character sets instead of creating reusable components like CharacterSet and PasswordGeneratorFactory
  10. Failing to test the Password Generator thoroughly with unit tests

Practice Questions

  1. Modify the Password Generator to include additional character sets (e.g., symbols, punctuation marks)
  2. Allow users to specify a custom password template (e.g., "3 uppercase letters, 4 lowercase letters, 2 numbers, and 1 special character")
  3. Implement a method to check the strength of a given password based on common password cracking techniques (e.g., using dictionary words, sequential patterns, etc.)
  4. Improve the user interface by providing options for copying the generated password or saving it to a file
  5. Optimize the Password Generator for better performance (e.g., reducing random character generation)
  6. Implement multi-threading to generate multiple passwords concurrently
  7. Create a GUI for the Password Generator using JavaFX or Swing
  8. Integrate the Password Generator into a web application using Java Servlets or Spring Boot
  9. Use the Password Generator to create secure API keys and tokens
  10. Implement a method to generate password hints based on the generated password

FAQ

Q: Why do we use the getRandomCharPercentage() method?

A: To control the ratio of randomly chosen characters vs pre-defined character sets in the generated password, improving its randomness and security.

Q: Can I customize the character sets used by the Password Generator?

A: Yes, you can add or modify the UPPERCASE_CHARS, LOWERCASE_CHARS, NUMBERS, and SPECIAL_CHARS constants to suit your needs.

Q: How do I ensure that the generated password is unique and not easily guessable?

A: By using a mix of character types, including uppercase letters, lowercase letters, numbers, and special characters, and avoiding common patterns or dictionary words. Additionally, you can implement methods to check the strength of a given password based on common password cracking techniques.

Q: Can I use this Password Generator in a web application?

A: Yes, you can create a Java web app using frameworks like Spring Boot to serve the Password Generator as a RESTful API or integrate it into a web page using JavaScript.

Q: Why is it essential to generate strong passwords for online security?

A: Strong passwords help protect against unauthorized access, data breaches, and account takeovers by making it harder for attackers to guess or crack your password. Additionally, they reduce the risk of compromising sensitive information stored in your online accounts.

Password Generator (Java) | Java | XQA Learn