Write a java program to validate the password.

Write java code to validate the password using following rules:

  • Must contain at least one digit
  •  Must contain at least one of the following special characters @, #, $
  • Length should be between 6 to 20 characters.

If the password is as per the given rules return 1 else return -1.If the return value is 1 then print valid password else print as the invalid password.

Input and Output Format:

Input is a string.

The output is a string.

Sample Input 1:


Sample Output 1:
Invalid password

Sample Input 2:


Sample Output 2:

Valid password

Password Validation in Java.

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String s1 = sc.nextLine();
        int n = UserMainCode.display(s1);
        	System.out.println("Valid password");
        	System.out.println("Invalid password");


class UserMainCode {
    public static int display(String password){
if(password.matches(".*[0-9]{1,}.*") && password.matches(".*[@#$]{1,}.*") && password.length()>=6 && password.length()<=20)
                                    return 1;
                                    return -1;




Add a Comment

Your email address will not be published. Required fields are marked *

sixteen − eight =