🧠 Introduction
In today’s digital world, password security is extremely important. Whether you’re building a web application, mobile app, or desktop software, generating strong random passwords helps protect user data from unauthorized access.
In Java, you can easily create random passwords using built-in classes like Random, SecureRandom, or even UUID. Each method has its own advantages, depending on how secure and random you want the password to be.
⚙️ Why Generate Random Passwords in Java?
Before jumping into the code, let’s understand why random password generation is important:
Security: Random passwords are hard to guess and protect against brute-force attacks.
Automation: Automatically generating passwords saves time during account creation or testing.
Consistency: Ensures password policies (like minimum length and character mix) are followed programmatically.
🧩 Step 1. Generate a Simple Random Password Using Random
The simplest way to generate random characters is by using the java.util.Random class.
Example
import java.util.Random;
public class SimplePasswordGenerator {
public static void main(String[] args) {
String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
StringBuilder password = new StringBuilder();
Random random = new Random();
int length = 10; // password length
for (int i = 0; i < length; i++) {
int index = random.nextInt(characters.length());
password.append(characters.charAt(index));
}
System.out.println("Generated Password: " + password);
}
}
📝 Explanation
We define a string of all possible characters (uppercase, lowercase, and numbers).
The
Randomobject picks a random index from that string.We append each random character to build the final password.
✅ Output
Generated Password: Af3LpXz91B
⚠️ Note: While this method works fine for basic use cases, it’s not cryptographically secure. For real-world applications (like user passwords), use SecureRandom.
🔒 Step 2. Generate a Secure Random Password Using SecureRandom
The SecureRandom class from java.security provides a stronger random number generator suitable for cryptographic purposes.
Example
import java.security.SecureRandom;
public class SecurePasswordGenerator {
public static void main(String[] args) {
String upperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String lowerCase = "abcdefghijklmnopqrstuvwxyz";
String numbers = "0123456789";
String symbols = "!@#$%^&*()_+-=[]{}|;:,.<>?";
String allChars = upperCase + lowerCase + numbers + symbols;
SecureRandom random = new SecureRandom();
StringBuilder password = new StringBuilder();
int length = 12; // secure password length
for (int i = 0; i < length; i++) {
int index = random.nextInt(allChars.length());
password.append(allChars.charAt(index));
}
System.out.println("Secure Password: " + password);
}
}

Join the conversation! Your thoughts help the community grow.