How to Validate PAN Number in Java Using Regex
Learn how to validate PAN number in Java using a regular expression. A PAN is a 10-character alphanumeric identifier. Its general format contains five uppercase letters, followed by four digits and one uppercase letter.
Code Explanation (Step-by-Step)
- The validatePanNumber() method accepts a PAN number as a String parameter.
- The method returns a Boolean value:
- true if the PAN number format is valid.
- false if the PAN number format is invalid.
- If the panNumber is null, the method returns false.
- The PAN validation regular expression used in the program is: ^[A-Z]{5}[0-9]{4}[A-Z]$
- The matches() method compares the entire PAN number with the specified regular expression .
- The first five characters must be uppercase English letters.
- The next four characters must be numeric digits.
- The last character must be an uppercase English letter.
- If the PAN number matches the required format, the method returns true; otherwise, it returns false.
- Finally, the program prints whether the given PAN number is valid or invalid.
public class ValidatePanNumber {
public static boolean validatePanNumber(String panNumber) {
if (panNumber == null) {
return false;
}
return panNumber.matches("^[A-Z]{5}[0-9]{4}[A-Z]$");
}
public static void main(String[] args) {
String[] panNumbers = {
"ACYPY0931A",
"ABCDe1234F",
"ABCD1234E",
"ABCDE12345",
null
};
for (String panNumber : panNumbers) {
System.out.println(
panNumber + " : " + validatePanNumber(panNumber)
);
}
}
}
Output :-
ACYPY0931A : true
ABCDe1234F : false
ABCD1234E : false
ABCDE12345 : false
null : false
Test Cases for PAN Number Validation in Java
public class ValidatePanNumber {
public static boolean validatePanNumber(String panNumber) {
if (panNumber == null) {
return false;
}
return panNumber.matches("^[A-Z]{5}[0-9]{4}[A-Z]$");
}
public static void main(String[] args) {
String[] panNumbers = {
"ACYPY0931A", // Valid PAN
"ABCDE1234F", // Valid PAN
"ABCD1234E", // Less than 10 characters
"ABCDE12345", // Ends with digit
"abcde1234F", // Lowercase letters
"ABCDE12A4F", // Contains letter in digit position
null // Null value
};
for (String panNumber : panNumbers) {
System.out.println(
"PAN Number: " + panNumber +
" -> Valid: " + validatePanNumber(panNumber)
);
}
}
}
Output :-
PAN Number: ACYPY0931A -> Valid: true
PAN Number: ABCDE1234F -> Valid: true
PAN Number: ABCD1234E -> Valid: false
PAN Number: ABCDE12345 -> Valid: false
PAN Number: abcde1234F -> Valid: false
PAN Number: ABCDE12A4F -> Valid: false
PAN Number: null -> Valid: false
Here are some Java-related programs that will help you understand Java concepts better: