Validate Password

Check if a password meets basic strength rules using regex.

IntermediateTopic: Module 4: String Programs
Back

Java Validate Password Program

This program helps you to learn the fundamental structure and syntax of Java programming.

Try This Code
import java.util.Scanner;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter password: ");
        String pwd = sc.nextLine();

        // At least 8 chars, one digit, one lower, one upper
        String regex = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{8,}$";
        boolean strong = Pattern.matches(regex, pwd);
        System.out.println(strong ? "Strong password" : "Weak password");
        sc.close();
    }
}
Output
Enter password: Abcdef1g
Strong password

Understanding Validate Password

We use lookahead-based regex to require digit, lowercase, uppercase, and minimum length.

Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.

Table of Contents